c# winform 选择文本文件 的示例
时间: 2023-07-28 17:10:04 浏览: 200
以下是一个简单的示例代码,用于在 C# WinForms 中选择并打开文本文件:
private void button1_Click(object sender, EventArgs e)
{
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)
{
// 获取文件路径
string filePath = openFileDialog1.FileName;
// 在此处打开文件或处理文件
// 例如,将文件内容显示在文本框中
textBox1.Text = File.ReadAllText(filePath);
}
}
在此示例中,我们使用 OpenFileDialog
控件来选择文本文件。 InitialDirectory
属性设置打开对话框时显示的初始目录,Filter
属性指定可用的文件过滤器,FilterIndex
属性设置默认文件过滤器的索引,RestoreDirectory
属性指示对话框是否在关闭后还原当前目录。
在 if
语句中,我们检查用户是否单击了“打开”按钮,如果是,则获取所选文件的路径并执行一些自定义操作,例如将文件内容显示在文本框中。
相关推荐


















