如何:动态显示 OpenFileDialog

更新:2007 年 11 月

借助 OpenFileDialog 组件,用户可浏览至文本文件并将选定的文件加载到 Windows 窗体上的 RichTextBox 控件。此示例在运行时实例化 OpenFileDialog

示例

// Create an OpenFileDialog object.
OpenFileDialog openFile1 = new OpenFileDialog();

// Initialize the OpenFileDialog to look for text files.
openFile1.Filter = "Text Files|*.txt";

// Check if the user selected a file from the OpenFileDialog.
if(openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)

    // Load the contents of the file into a RichTextBox control.
    richTextBox1.LoadFile(openFile1.FileName,
    RichTextBoxStreamType.PlainText);

编译代码

  • 将代码复制到 Load_Form1 事件处理程序中。程序运行时,将提示您选择文本文件。选定文件的内容将显示在 RichTextBox 控件中。

可靠编程

使用 OpenFileDialog 控件的 CheckFileExistsCheckPathExistsDefaultExtFilterMultiselectValidateNames 属性可限制运行时错误。

请参见

概念

在 Visual C# 中设计用户界面

其他资源

对话框 (Visual C#)

Visual C# 指导教程