yas17
yas17

Reputation: 421

Read stream in C#

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?

Upvotes: 2

Views: 28356

Answers (1)

Oswald
Oswald

Reputation: 1272

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());
    }
}

Upvotes: 9

Related Questions