Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read stream in C#

Tags:

c#

stream

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?

like image 636
yas17 Avatar asked Aug 10 '26 18:08

yas17


1 Answers

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());
    }
}
like image 57
Oswald Avatar answered Aug 12 '26 06:08

Oswald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!