uccjshrimpton

C# Reading from a File

Nov 15th, 2016
935
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.28 KB | None | 0 0
  1.             // The files used in this example are created in the topic
  2.             // How to: Write to a Text File. You can change the path and
  3.             // file name to substitute text files of your own.
  4.  
  5.             // Example #1
  6.             // Read the file as one string.
  7.             string text = System.IO.File.ReadAllText(@"S:\Visual Studio 2015\Projects\WriteText.txt");
  8.  
  9.             // Display the file contents to the console. Variable text is a string.
  10.             System.Console.WriteLine("Contents of WriteText.txt = {0}", text);
  11.  
  12.             // Example #2
  13.             // Read each line of the file into a string array. Each element
  14.             // of the array is one line of the file.
  15.             string[] lines = System.IO.File.ReadAllLines(@"S:\Visual Studio 2015\Projects\WriteLines2.txt");
  16.  
  17.             // Display the file contents by using a foreach loop.
  18.             System.Console.WriteLine("Contents of WriteLines2.txt = ");
  19.             foreach (string line in lines)
  20.             {
  21.                 // Use a tab to indent each line of the file.
  22.                 Console.WriteLine("\t" + line);
  23.             }
  24.  
  25.             // Keep the console window open in debug mode.
  26.             Console.WriteLine("Press any key to exit.");
  27.             System.Console.ReadKey();
Advertisement
Add Comment
Please, Sign In to add comment