如何:使用 OpenFileDialog 打开文件
System.Windows.Forms.OpenFileDialog 组件将打开用于浏览和选择文件的 Windows 对话框。 若要打开并读取所选文件,可使用 OpenFileDialog.OpenFile 方法或创建 System.IO.StreamReader 类的实例。 下面的示例将演示这两种方法。
在 .NET Framework 中,若要获取或设置 FileName 属性,需要 System.Security.Permissions.FileIOPermission 类授予的权限级别。 示例运行 FileIOPermission 权限检查,如果是在部分信任的上下文中运行,可能会由于权限不足而引发异常。 有关详细信息,请参阅代码访问安全性基础知识。
可以通过 C# 或 Visual Basic 命令行将这些示例作为 .NET Framework 应用生成和运行。 有关详细信息,请参阅在命令行上使用 csc.exe 生成或从命令行生成。
从 .NET Core 3.0 开始,你还可以从具有 .NET Core Windows 窗体 <folder name>.csproj 项目文件的文件夹将这些示例作为 Windows .NET Core 应用生成和运行。
示例:使用 StreamReader 以流的形式读取文件
以下示例使用 Windows 窗体 Button 控件的 Click 事件处理程序通过 ShowDialog 方法打开 OpenFileDialog。 用户选择一个文件并选择“确定”后,StreamReader 类的实例将读取该文件,并在窗体的文本框中显示文件内容。 若要详细了解如何从文件流读取,请参阅 FileStream.BeginRead 和 FileStream.Read。
using System;
using System.Drawing;
using System.IO;
using System.Security;
using System.Windows.Forms;
public class OpenFileDialogForm : Form
{
[STAThread]
public static void Main()
{
Application.SetCompatibleTextRenderingDefault(false);
Application.EnableVisualStyles();
Application.Run(new OpenFileDialogForm());
}
private Button selectButton;
private OpenFileDialog openFileDialog1;
private TextBox textBox1;
public OpenFileDialogForm()
{
openFileDialog1 = new OpenFileDialog();
selectButton = new Button
{
Size = new Size(100, 20),
Location = new Point(15, 15),
Text = "Select file"
};
selectButton.Click += new EventHandler(SelectButton_Click);
textBox1 = new TextBox
{
Size = new Size(300, 300),
Location = new Point(15, 40),
Multiline = true,
ScrollBars = ScrollBars.Vertical
};
ClientSize = new Size(330, 360);
Controls.Add(selectButton);
Controls.Add(textBox1);
}
private void SetText(string text)
{
textBox1.Text = text;
}
private void SelectButton_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
var sr = new StreamReader(openFileDialog1.FileName);
SetText(sr.ReadToEnd());
}
catch (SecurityException ex)
{
MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
$"Details:\n\n{ex.StackTrace}");
}
}
}
}
Imports System.Drawing
Imports System.IO
Imports System.Security
Imports System.Windows.Forms
Public Class OpenFileDialogForm : Inherits Form
Public Shared Sub Main()
Application.SetCompatibleTextRenderingDefault(False)
Application.EnableVisualStyles()
Dim frm As New OpenFileDialogForm()
Application.Run(frm)
End Sub
Dim WithEvents SelectButton As Button
Dim openFileDialog1 As OpenFileDialog
Dim TextBox1 As TextBox
Private Sub New()
ClientSize = New Size(400, 400)
openFileDialog1 = New OpenFileDialog()
SelectButton = New Button()
With SelectButton
.Text = "Select file"
.Location = New Point(15, 15)
.Size = New Size(100, 25)
End With
TextBox1 = New TextBox()
With TextBox1
.Size = New Size(300, 300)
.Location = New Point(15, 50)
.Multiline = True
.ScrollBars = ScrollBars.Vertical
End With
Controls.Add(SelectButton)
Controls.Add(TextBox1)
End Sub
Private Sub SetText(text)
TextBox1.Text = text
End Sub
Public Sub SelectButton_Click(sender As Object, e As EventArgs) _
Handles SelectButton.Click
If openFileDialog1.ShowDialog() = DialogResult.OK Then
Try
Dim sr As New StreamReader(openFileDialog1.FileName)
SetText(sr.ReadToEnd())
Catch SecEx As SecurityException
MessageBox.Show($"Security error:{vbCrLf}{vbCrLf}{SecEx.Message}{vbCrLf}{vbCrLf}" &
$"Details:{vbCrLf}{vbCrLf}{SecEx.StackTrace}")
End Try
End If
End Sub
End Class
示例:使用 OpenFile 从筛选的选择中打开文件
以下示例使用 Button 控件的 Click 事件处理程序打开包含仅显示文本文件的筛选器的 OpenFileDialog。 用户选择文本文件并选择“确定”后,可用 OpenFile 方法在记事本中打开该文件。
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Security;
using System.Windows.Forms;
public class OpenFileDialogForm : Form
{
[STAThread]
public static void Main()
{
Application.SetCompatibleTextRenderingDefault(false);
Application.EnableVisualStyles();
Application.Run(new OpenFileDialogForm());
}
private Button selectButton;
private OpenFileDialog openFileDialog1;
public OpenFileDialogForm()
{
openFileDialog1 = new OpenFileDialog()
{
FileName = "Select a text file",
Filter = "Text files (*.txt)|*.txt",
Title = "Open text file"
};
selectButton = new Button()
{
Size = new Size(100, 20),
Location = new Point(15, 15),
Text = "Select file"
};
selectButton.Click += new EventHandler(selectButton_Click);
Controls.Add(selectButton);
}
private void selectButton_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
var filePath = openFileDialog1.FileName;
using (Stream str = openFileDialog1.OpenFile())
{
Process.Start("notepad.exe", filePath);
}
}
catch (SecurityException ex)
{
MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
$"Details:\n\n{ex.StackTrace}");
}
}
}
}
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.IO
Imports System.Security
Imports System.Windows.Forms
Public Class OpenFileDialogForm : Inherits Form
Dim WithEvents selectButton As Button
Dim openFileDialog1 As OpenFileDialog
Public Shared Sub Main()
Application.SetCompatibleTextRenderingDefault(false)
Application.EnableVisualStyles()
Dim frm As New OpenFileDialogForm()
Application.Run(frm)
End Sub
Private Sub New()
openFileDialog1 = New OpenFileDialog() With
{
.FileName = "Select a text file",
.Filter = "Text files (*.txt)|*.txt",
.Title = "Open text file"
}
selectButton = New Button() With {.Text = "Select file"}
Controls.Add(selectButton)
End Sub
Public Sub selectButton_Click(sender As Object, e As EventArgs) _
Handles selectButton.Click
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Try
Dim filePath = OpenFileDialog1.FileName
Using str = openFileDialog1.OpenFile()
Process.Start("notepad.exe", filePath)
End Using
Catch SecEx As SecurityException
MessageBox.Show($"Security error:{vbCrLf}{vbCrLf}{SecEx.Message}{vbCrLf}{vbCrLf}" &
$"Details:{vbCrLf}{vbCrLf}{SecEx.StackTrace}")
End Try
End If
End Sub
End Class