C# 选择文件 选择文件夹 无响应 闪退问题
选择文件 OpenFileDialog 使用注释中的即可
private static OpenFileDialog openFileDialog;
private static DialogResult result1;
/// <summary>
/// 打开文件
/// </summary>
/// <param name="textBox">文本框</param>
/// <param name="FilePath">文件路径</param>
/// <param name="filter">文件后缀名</param>
public static void OpenFile(TextBox textBox, ref string FilePath,string filter = "excel|*.xls;*.XLS;*.xlsx;*.XLSX")
{
openFileDialog = new OpenFileDialog
{
Title = "请选择文件路径",
InitialDirectory = System.IO.Path.GetDirectoryName(textBox.Text),
Filter = filter,
Multiselect = false,
CheckFileExists = true,
CheckPathExists = true
};
result1 = openFileDialog.ShowDialog();
//长时间未响应使用线程可解决
//var invokeThread = new Thread(() => result1 = openFileDialog.ShowDialog());
//invokeThread.SetApartmentState(ApartmentState.STA);
//invokeThread.Start();
//invokeThread.Join();
if (result1 == DialogResult.OK)
{
FilePath = openFileDialog.FileName;
textBox.Text = FilePath;
}
}
选择文件夹 FolderBrowserDialog 使用注释中的即可
private static FolderBrowserDialog folderBrowserDialog;
private static DialogResult result2;
/// <summary>
/// 打开文件夹
/// </summary>
/// <param name="textBox">文本框</param>
/// <param name="folderPath">文件夹路径</param>
public static void OpenFolder(TextBox textBox, ref string folderPath)
{
folderBrowserDialog = new FolderBrowserDialog
{
Description = "请选择文件夹",
SelectedPath = textBox.Text,
};
result2 = folderBrowserDialog.ShowDialog();
//长时间未响应使用线程可解决
//var invokeThread = new Thread(() => result2 = folderBrowserDialog.ShowDialog());
//invokeThread.SetApartmentState(ApartmentState.STA);
//invokeThread.Start();
//invokeThread.Join();
if (result2 == DialogResult.OK)
{
folderPath = folderBrowserDialog.SelectedPath;
textBox.Text = folderPath;
}
}