C# 中读取流

yas*_*s17 2 c# stream

我有这段代码用于读取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));
Run Code Online (Sandbox Code Playgroud)

此代码有效,但如果我更改标记行中的零,则MessageBox不会显示任何内容。

我该如何解决这个问题?

Osw*_*ald 7

这是您要读取的部分的起始索引,如果您更改此值,则不会从头开始读取文件。

要从文件中读取内容,这是我最喜欢的方法:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)