C# - Read .txt file into TextBox(C# - 将 .txt 文件读入文本框)
问题描述
我正在尝试使用以下代码将 .txt 文件读入多行文本框中.我已经让文件对话框按钮完美工作,但我不确定如何将文件中的实际文本获取到文本框中.这是我的代码.你能帮忙吗?
I am trying to read a .txt file into a multi-line text box with the following code. I have gotten the file dialog button to work perfectly, but I am not sure how to get the actual text from the fiile into the textbox. Here is my code. Can you help?
private void button_LoadSource_Click(object sender, EventArgs e)
{
Stream myStream = 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 ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
推荐答案
如果你只需要完整的文本,你应该使用函数File.ReadAllText
- 将对话框中选择的文件名/路径传递给它 (openFileDialog1.FileName
).
if you just need the complete text, you should use the function File.ReadAllText
- pass it the FileName/Path selected in the dialoge (openFileDialog1.FileName
).
例如要将内容加载到文本框中,您可以编写:
to load for example the content into a textbox, you can write:
textbox1.Text = File.ReadAllText(openFileDialog1.FileName);
打开和使用流有点复杂,你应该查看 using - 语句
opening and using streams is a little bit more complicated, for that you should look up the using - statement
这篇关于C# - 将 .txt 文件读入文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# - 将 .txt 文件读入文本框


- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 使用 rss + c# 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01