如何:使用 OpenFileDialog 组件打开文件 - Windows Forms

如何:使用 OpenFileDialog 组件打开文件 - Windows Forms

该 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 窗体 <文件夹名称>.csproj 项目文件的文件夹生成并运行示例作为 Windows .NET Core 应用。

示例:使用 StreamReader 以流的形式读取文件

以下示例使用 Windows 窗体 Button 控件的 Click 事件处理程序,通过 OpenFileDialog 方法打开 ShowDialog。 用户选择文件并选择 “确定”后,类的 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

另请参阅

OpenFileDialog

OpenFileDialog 组件

相关推荐