OpenFileDialog là một lớp trong namespace System.Windows.Forms, dùng để hiển thị hộp thoại chọn tệp chuẩn của Windows, cho phép người dùng chọn tệp để mở trong ứng dụng WinForms.
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog.FileName;
// Xử lý filePath (ví dụ đọc nội dung tệp)
}ShowDialog là 1 hàm trả về các giá trị
ShowDialog() trả về một giá trị kiểu DialogResult, là enum có sẵn trong .NET, biểu thị cách người dùng đóng form.
DialogResult.OK Người dùng nhấn nút OK
DialogResult.Cancel Người dùng nhấn Cancel hoặc đóng form bằng nút X
DialogResult.Yes Người dùng nhấn Yes
DialogResult.No Người dùng nhấn No
DialogResult.Abort Người dùng chọn Abort
DialogResult.Retry Người dùng chọn Retry
DialogResult.Ignore Người dùng chọn Ignore
DialogResult.None Form chưa trả về kết quả nào
| Thuộc tính | Kiểu dữ liệu | Chức năng |
|---|---|---|
FileName |
string |
Lấy đường dẫn đầy đủ của tệp đã chọn. |
Filter |
string |
Giới hạn kiểu tệp hiển thị, ví dụ: `"Text files (*.txt) |
Title |
string |
Tiêu đề của hộp thoại. |
Multiselect |
bool |
Cho phép chọn nhiều tệp cùng lúc. |
InitialDirectory |
string |
Thư mục hiển thị ban đầu. |
DefaultExt |
string |
Phần mở rộng mặc định. |
CheckFileExists |
bool |
Mặc định true. Nếu false, cho phép nhập tên tệp không tồn tại. |
private void btnChonFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Chọn tệp văn bản";
ofd.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
string path = ofd.FileName;
string content = File.ReadAllText(path);
MessageBox.Show(content, "Nội dung tệp");
}
}private void btnChonNhieuFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
ofd.Filter = "All files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
string[] selectedFiles = ofd.FileNames;
foreach (string file in selectedFiles)
{
MessageBox.Show("Tệp được chọn: " + file);
}
}
}private void btnChonAnh_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Image Files (*.jpg;*.jpeg;*.png)|*.jpg;*.jpeg;*.png";
if (ofd.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = Image.FromFile(ofd.FileName);
}
} ShowDialog() là phương thức chặn (blocking), nó sẽ dừng chương trình cho đến khi người dùng đóng hộp thoại.
Luôn kiểm tra DialogResult == DialogResult.OK trước khi xử lý tệp.
Có thể thêm kiểm tra tồn tại tệp với File.Exists(path) nếu cần chắc chắn.
Bài 1
Bài 2
Nhiều bài tập liên quan trong [Khóa học Winform cơ bản]
Tìm kiếm:
Hướng dẫn cách sử dụng Hộp thoại hiện thị OpenFileDialog C#