Posted By

alirezanoori on 07/19/10


Tagged

text Reading Large fileslarge fielstext fiels


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

Vordreller
Tyster


Large Files


 / Published in: C#
 

  1. namespace CSConsole
  2. {
  3. public class Program
  4. {
  5. public static void Main()
  6. {
  7. //calling the function for asccii file with 500 bytes of size
  8. ReadBinaryFile("C:\\Temp\\sth.txt", Encoding.ASCII, 500);
  9. }
  10.  
  11. private static void ReadBinaryFile(string path, Encoding encoding, int bufferSize)
  12. {
  13. try
  14. {
  15. byte[] buffer = new byte[bufferSize];
  16. string line, whole, halfLine = string.Empty;
  17. using (FileStream fileStream = File.Open(path, FileMode.Open, FileAccess.Read))
  18. {
  19. while (fileStream.Position < fileStream.Length)
  20. {
  21. int len = fileStream.Read(buffer, 0, buffer.Length);
  22. whole = encoding.GetString(buffer, 0, len);
  23.  
  24. string[] lines = whole.Replace("
  25. ", "\n").Split('\n');
  26. int lineCount = lines.Length;
  27.  
  28. if (halfLine != null)
  29. lines[0] = halfLine + lines[0];
  30.  
  31. if (buffer[len - 1] != 10)
  32. {
  33. halfLine = lines[lines.Length - 1];
  34. lineCount--;
  35. }
  36. else
  37. {
  38. halfLine = null;
  39. }
  40.  
  41. for (int i = 0; i < lineCount; i++)
  42. {
  43. //YOUR CODE GOES HERE. NO NEED TO CHANGE ANYTHING ELSE!!!
  44. ProcessLine(lines[i]);
  45. }
  46. }
  47. }
  48. }
  49. catch (Exception ex)
  50. {
  51. //ERROR!!
  52. }
  53. }
  54.  
  55. private static int globalLine = 0;
  56. private static void ProcessLine(string line)
  57. {
  58. Console.WriteLine(globalLine + ". " + line);
  59. globalLine++;
  60. }
  61. }
  62. }

Report this snippet  

You need to login to post a comment.