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;
    }
}

相关推荐:
https://www.thinbug.com/q/8897076

posted on   糯米白白  阅读(611)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示