Uwaga
Dostęp do tej strony wymaga autoryzacji. Może spróbować zalogować się lub zmienić katalogi.
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zmienić katalogi.
Składnik System.Windows.Forms.OpenFileDialog otwiera okno dialogowe systemu Windows do przeglądania i wybierania plików. Aby otworzyć i odczytać wybrane pliki, możesz użyć metody OpenFileDialog.OpenFile lub utworzyć wystąpienie klasy System.IO.StreamReader. W poniższych przykładach przedstawiono oba podejścia.
W programie .NET Framework, aby pobrać lub ustawić właściwość FileName wymaga poziomu uprawnień przyznanego przez klasę System.Security.Permissions.FileIOPermission. Przykłady wykonują sprawdzenie uprawnień FileIOPermission i mogą zgłosić wyjątek z powodu braku wystarczających uprawnień, jeśli są uruchamiane w kontekście częściowego zaufania. Aby uzyskać więcej informacji, zobacz Podstawy zabezpieczeń dostępu do kodu.
Możesz skompilować i uruchomić te przykłady jako aplikacje .NET Framework z poziomu wiersza polecenia języka C# lub Visual Basic. Aby uzyskać więcej informacji, zobacz kompilowanie wiersza polecenia za pomocą csc.exe lub Build z wiersza polecenia.
Począwszy od .NET Core 3.0, można również skompilować i uruchomić przykłady jako aplikacje Windows .NET Core z folderu, który ma nazwę folderu .NET Core Windows Forms <, oraz zawiera plik projektu>.csproj.
Przykład: Odczytywanie pliku jako strumienia za pomocą elementu StreamReader
W poniższym przykładzie użyto procedury obsługi zdarzeń Button kontrolki Windows Forms Click, aby otworzyć OpenFileDialog za pomocą metody ShowDialog. Gdy użytkownik wybierze plik i wybierze OK, wystąpienie klasy StreamReader odczytuje plik i wyświetla jego zawartość w polu tekstowym formularza. Aby uzyskać więcej informacji na temat odczytywania ze strumieni plików, zobacz FileStream.BeginRead i 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
Przykład: Otwórz plik z filtrowanego zaznaczenia za pomocą OpenFile
W poniższym przykładzie użyto programu obsługi zdarzeń Button kontrolki Click, aby otworzyć OpenFileDialog z filtrem, który wyświetla tylko pliki tekstowe. Gdy użytkownik wybierze plik tekstowy i wybierze OK, metoda OpenFile jest używana do otwierania pliku w Notatniku.
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
Zobacz także
.NET Desktop feedback