1

Is there any Stream reader Class to read only number of char from string Or byte from byte[]?

forexample reading string:

string chunk = streamReader.ReadChars(5); // Read next 5 chars

or reading bytes

byte[] bytes = streamReader.ReadBytes(5); // Read next 5 bytes

Note that the return type of this method or name of the class does not matter. I just want to know if there is some thing similar to this then i can use it.

I have byte[] from midi File. I want to Read this midi file in C#. But i need ability to read number of bytes. or chars(if i convert it to hex). To validate midi and read data from it more easily.

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
  • 1
    You can use [StreamReader.Read](https://msdn.microsoft.com/en-us/library/9kstw824(v=vs.110).aspx) - "Reads a specified maximum of characters from the current stream into a buffer, beginning at the specified index." – stuartd Jul 01 '15 at 23:44
  • 1
    You probably looking for `BinaryReader`. Classes deriving from `TextReader` are generally text-oriented... Note that all of them require `Stream` as source - which is what `MemoryStream` for. – Alexei Levenkov Jul 01 '15 at 23:50
  • @AlexeiLevenkov Thank you. Your comment was actually an answer. what i need is MemoryStream. – M.kazem Akhgary Jul 02 '15 at 00:11
  • @M.kazemAkhgary - ok - consider to find good duplicate... or convert my answer to comment if you want. I though [similar question](http://stackoverflow.com/questions/16598021/how-to-read-byte-with-current-encoding-using-streamreader) that asks about particular encoding would be ok duplicate, but it already shows answer in the question - so not really fair. – Alexei Levenkov Jul 02 '15 at 00:14
  • yes. i got it. how ever i dont need stream reader. because i need bytes even for Hex i need bytes too and memorystream read bytes. @AlexeiLevenkov – M.kazem Akhgary Jul 02 '15 at 00:20

2 Answers2

2

Thanks for the comments. I didnt know there is an Overload for Read Methods. i could achieve this with FileStream.

        using (FileStream fileStream = new FileStream(path, FileMode.Open))
        {
            byte[] chunk = new byte[4];
            fileStream.Read(chunk, 0, 4);
            string hexLetters = BitConverter.ToString(chunk); // 4 Hex Letters that i need!
        }
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
0

You can achieve this by doing something like below but I am not sure this will applicable for your problem or not.

 StreamReader sr = new StreamReader(stream);
 StringBuilder S = new StringBuilder();
 while(true)
 {
 S = S.Append(sr.ReadLine());
 if (sr.EndOfStream  == true)
      {
         break;
      }
 }

Once you have value on "S", you can consider sub strings from it.

Raj Karri
  • 551
  • 4
  • 19