无法将类型'System.IO.Stream'隐式转换为'System.IO.StreamReader

时间:2014-02-19 16:53:33

标签: c#

这是我的代码。我似乎无法使用openFileDialog和我使用StreamReader的方式?请任何想法。

        StreamReader reader = null;


        OpenFileDialog openFileDialog1 = new OpenFileDialog();

        openFileDialog1.InitialDirectory = "c:\\";
        openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.RestoreDirectory = true;

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            try
            {
                if ((reader = openFileDialog1.OpenFile()) != null)
                {
                    using (reader)
                    {
                        textBox2.Text = reader.ReadLine();
                        textBox3.Text = reader.ReadLine();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
            }
        }

谢谢。

1 个答案:

答案 0 :(得分:8)

OpenFileDialog.OpenFile() returns a Stream

if ((var stream = openFileDialog1.OpenFile()) != null)
{
    using (var reader = new StreamReader(stream))
    {
        // ...
    }
}

或者,你可以省略手动获取流并在其后面进行丑陋的空检查(它会随时返回null,还是抛出异常?):

using (reader = new StreamReader(openFileDialog1.Filename))
{
    // ...
}