2

I have this code for reading from a Stream:

OpenFileDialog op = new OpenFileDialog();
op.ShowDialog();
Stream stream = File.Open(op.FileName,FileMode.Open);
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, 10); // Problem is in this line
MessageBox.Show(System.Text.Encoding.UTF8.GetString(bytes));

This code works, but if I change the zero in the marked line then the MessageBox doesn't show anything.

How can I resolve this problem?

4
  • 1
    Question is unclear...change zero to what? What is the problem? What is the expected behaviour?
    – Abhay
    Sep 20, 2017 at 5:30
  • UTF8 characters can span multiple bytes, consider using an Encoder to maintain state between reads or, if the data contains ASCII, use ASCII encoding to decode. As for the messagebox not showing anything - what data did you expect to see?
    – C.Evenhuis
    Sep 20, 2017 at 6:32
  • Possible duplicate of Reading large file in chunks c# Sep 20, 2017 at 6:51
  • ^^ Duplicate suggestion because of the comment to answer: "think you have a 10 GB file and you want read this file with parts". Sep 20, 2017 at 6:52

1 Answer 1

6

That's the start-index of the part your're gonna read, if you change this, you do not read from the file from start on.

To read content from files, this is my favourite methode to do this:

using (var op = new OpenFileDialog())
{
    if (op.ShowDialog() != DialogResult.OK)
        return;
    using (var stream = System.IO.File.OpenRead(op.FileName))
    using (var reader = new StreamReader(stream))
    {
        MessageBox.Show(reader.ReadToEnd());
    }
}
2
  • bro thanks. think you have a 10 GB file and you want read this file with parts example part1=50000bytes part2=50000 bytes and.... how to do this with stream?
    – yas17
    Sep 20, 2017 at 5:48
  • The StreamReader class provides some other methods to read too. I use this class because there is the whole handling with the reading mechanisms already made
    – Oswald
    Sep 20, 2017 at 5:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.