当我尝试打开.txt
文件时,它只在textbox
中显示其位置。
我没有想法:(希望你能帮助我......
代码:
private void OpenItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
System.IO.StringReader OpenFile = new System.IO.StringReader(openFileDialog1.FileName);
richTextBox1.Text = OpenFile.ReadToEnd();
OpenFile.Close();
}
答案 0 :(得分:2)
我使用File.OpenText()
方法来阅读文本文件。您还应该使用using
语句来正确处理对象。
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
// Make sure a file was selected
if ((myStream = openFileDialog1.OpenFile()) != null) {
// Open stream
using (StreamReader sr = File.OpenText(openFileDialog1.FileName))
{
// Read the text
richTextBox1.Text = sr.ReadToEnd();
}
}
}
catch (Exception ex)
{
MessageBox.Show("An error occured: " + ex.Message);
}
}
答案 1 :(得分:2)
richTextBox1.Text = File.ReadAllText(openFileDialog1.FileName);
答案 2 :(得分:1)
StringReader
从您传递给它的字符串中读取字符 - 在本例中为文件的名称。如果要阅读文件内容,请使用StreamReader
:
var OpenFile = new System.IO.StreamReader(openFileDialog1.FileName);
richTextBox1.Text = OpenFile.ReadToEnd();
答案 3 :(得分:1)
这很容易。这是你需要做的:
1)将using System.IO;
放在命名空间之上。
2)创建一个新方法:
public static void read()
{
StreamReader readme = null;
try
{
readme = File.OpenText(@"C:\path\to\your\.txt\file.txt");
Console.WriteLine(readme.ReadToEnd());
}
// will return an invalid file name error
catch (FileNotFoundException errorMsg)
{
Console.WriteLine("Error, " + errorMsg.Message);
}
// will return an invalid path error
catch (Exception errorMsg)
{
Console.WriteLine("Error, " + errorMsg.Message);
}
finally
{
if (readme != null)
{
readme.Close();
}
}
}
3)在您的主要方法中调用它:read();
4)你已经完成了!