Code Snippets

  

C# Source Code


Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 131,962 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 2,060 people online right now. Registration is fast and FREE... Join Now!





Working with text files

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
Actions:
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. // 1) Write to a text file
  2. public void WriteToFile(string file)
  3. {
  4.     //create a TextWriter then open the file
  5.     TextWriter writer = new StreamWriter(file);
  6.     //now write the date to the file
  7.     writer.WriteLine(DateTime.Now);
  8.     //close the writer
  9.     writer.Close();
  10. }
  11.  
  12. // 2) Read a single line from text file
  13. public void readALine(string file)
  14. {
  15.     //create a new TextReader then open the file
  16.     TextReader reader = new StreamReader(file);
  17.     //read a single line from the file
  18.     reader.ReadLine();
  19. }
  20.  
  21. // 3) Read entire file into a variable then
  22. // return the contenxt
  23. public string ReadWholeFile(string file)
  24. {
  25.      //create a string variable to hold the file contents
  26.      string fileContents;
  27.      //create a new TextReader then open the file
  28.      TextReader reader = new StreamReader(file);
  29.      //loop through the entire file
  30.      while (reader.Peek() != -1)
  31.      {
  32.          //add each line to the fileContents variable
  33.          fileContents += reader.ReadLine().ToString();
  34.      }
  35.      //close the reader
  36.      reader.Close()
  37.      //return the results
  38.      return fileContents;
  39. }

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month