What's Here?
- Members: 131,962
- Replies: 470,238
- Topics: 72,883
- Snippets: 2,538
- Tutorials: 664
- Total Online: 2,060
- Members: 89
- Guests: 1,971
Who's Online?
|
Here are 3 snippets for reading text files in C#. 1 to write to a text file, one to read a single line of a text file anf one to read the whole file, place it into a variable
|
Submitted By: PsychoCoder
|
|
Rating:
   
|
|
Views: 1,820 |
Language: C#
|
|
Last Modified: August 31, 2007 |
|
Instructions: Each method has a single parameter, the file name you wish to work with. |
Snippet
// 1) Write to a text file
public void WriteToFile(string file)
{
//create a TextWriter then open the file
TextWriter writer = new StreamWriter (file );
//now write the date to the file
writer.WriteLine(DateTime.Now);
//close the writer
writer.Close();
}
// 2) Read a single line from text file
public void readALine(string file)
{
//create a new TextReader then open the file
TextReader reader = new StreamReader (file );
//read a single line from the file
reader.ReadLine();
}
// 3) Read entire file into a variable then
// return the contenxt
public string ReadWholeFile(string file)
{
//create a string variable to hold the file contents
string fileContents;
//create a new TextReader then open the file
TextReader reader = new StreamReader (file );
//loop through the entire file
while (reader.Peek() != -1)
{
//add each line to the fileContents variable
fileContents += reader.ReadLine().ToString();
}
//close the reader
reader.Close()
//return the results
return fileContents;
}
Copy & Paste
|
|
|
Reference Sheets
Bye Bye Ads
Free DIC T-Shirt
Related Sites
Monthly Drawing
Partners
Top Contributors
Top 10 Kudos This Month
|