Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Reading from a file in C#

Give the file name with path and watch the content in your console window.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6.  
  7. namespace ConsoleApplication3
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. string fileName = "D:\\tmp.txt";
  14. FileStream fileStream = null;
  15. try
  16. {
  17. fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  18. StreamReader sReader = new StreamReader(fileStream);
  19. string line;
  20. while ((line = sReader.ReadLine()) != null)
  21. {
  22. Console.WriteLine(line);
  23. }
  24. }
  25. catch (Exception e)
  26. {
  27. Console.WriteLine(e);
  28. }
  29. finally
  30. {
  31. if (fileStream != null)
  32. {
  33. fileStream.Close();
  34. }
  35. }
  36. }
  37. }
  38. }
  39.