Ram Prasad

Ram Prasad

  • NA
  • 326
  • 18.4k

Reading alphanumeric data from text file

Jun 7 2020 7:14 PM
I am using the code below to read binary data from text file and divide it into small chunks. I want to do the same with a text file with alphanumeric data which is obviously not working with the binary reader. Which reader would be best to achieve that stream,string or text and how to implement that in the following code?
  1. public static IEnumerable < IEnumerable < byte >> ReadByChunk(int chunkSize) {  
  2.  IEnumerable < byte > result;  
  3.  int startingByte = 0;  
  4.  do {  
  5.   result = ReadBytes(startingByte, chunkSize);  
  6.   startingByte += chunkSize;  
  7.   yield  
  8.   return result;  
  9.  }  
  10.  while (result.Any());  
  11. }  
  12. public static IEnumerable < byte > ReadBytes(int startingByte, int byteToRead) {  
  13.  byte[] result;  
  14.  using(FileStream stream = File.Open(@ "C:\Users\file.txt", FileMode.Open, FileAccess.Read,  
  15.   FileShare.Read))  
  16.  using(BinaryReader reader = new BinaryReader(stream)) {  
  17.   int bytesToRead = Math.Max(Math.Min(byteToRead, (int) reader.BaseStream.Length -  
  18.    startingByte), 0);  
  19.   reader.BaseStream.Seek(startingByte, SeekOrigin.Begin);  
  20.   result = reader.ReadBytes(bytesToRead);  
  21.  }  
  22.  return result;  
  23. }  

Answers (1)