gpt4 book ai didi

C# - 将 .txt 文件读入 TextBox

转载 作者:太空狗 更新时间:2023-10-29 23:55:15 24 4
gpt4 key购买 nike

我正在尝试使用以下代码将 .txt 文件读入多行文本框。我已经让文件对话框按钮正常工作,但我不确定如何将实际文本从文件中获取到文本框中。这是我的代码。你能帮忙吗?

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 )。

例如,要将内容加载到文本框中,您可以这样写:

 textbox1.Text = File.ReadAllText(openFileDialog1.FileName);

打开和使用流有点复杂,为此你应该查看 using - 语句

关于C# - 将 .txt 文件读入 TextBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13900441/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com