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;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?