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?

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
yas17
  • 401
  • 1
  • 3
  • 14
  • 1
    Question is unclear...change zero to what? What is the problem? What is the expected behaviour? – Abhay Sep 20 '17 at 05: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 '17 at 06:32
  • Possible duplicate of [Reading large file in chunks c#](https://stackoverflow.com/questions/21726260/reading-large-file-in-chunks-c-sharp) – Fildor Sep 20 '17 at 06:51
  • ^^ Duplicate suggestion because of the comment to answer: "think you have a 10 GB file and you want read this file with parts". – Fildor Sep 20 '17 at 06:52

1 Answers1

7

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());
    }
}
Oswald
  • 1,252
  • 20
  • 32
  • 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 '17 at 05: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 '17 at 05:49