You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用VistaFolderBrowserDialog时如何保存选中路径并成功加载回填?

问题原因
  • 参数传递逻辑错误:C#中string为不可变引用类型,参数默认按值传递,你在LoadFile方法内对loadTo参数的赋值仅修改了方法内部的局部变量副本,完全不会影响外部传入的文本框Text属性。
  • 文件名不匹配:选择路径保存时使用的文件名为radarpath/satellitepath,启动加载时使用的文件名是radarpath.txt/satellitepath.txt,后缀不一致导致程序无法找到已保存的文件。
  • 保存时机错误:你选择路径后先执行保存逻辑、再给文本框赋值新路径,最终保存的是修改前的旧路径,而非用户刚选中的新路径。
修复方案

1. 修改LoadFile方法为返回值形式

直接返回读取到的路径内容,避免参数传递问题:

private string LoadFile(string fileName)
{
    string applicationPath = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory);
    string saveFilePath = Path.Combine(applicationPath, fileName);
    return File.Exists(saveFilePath) ? File.ReadAllText(saveFilePath) : string.Empty;
}

2. 统一文件名并调整保存时机

统一使用带.txt的文件名,先给文本框赋值再执行保存:

private void btnRadarFolder_Click(object sender, RoutedEventArgs e)
{
    VistaFolderBrowserDialog dlg = new VistaFolderBrowserDialog();
    dlg.ShowNewFolderButton = true;
    if (dlg.ShowDialog() == true)
    {
        textBoxRadarFolder.Text = dlg.SelectedPath;
        SaveFile(textBoxRadarFolder.Text, "radarpath.txt");
    }
}

private void btnSatelliteFolder_Click(object sender, RoutedEventArgs e)
{
    VistaFolderBrowserDialog dlg = new VistaFolderBrowserDialog();
    dlg.ShowNewFolderButton = true;
    if (dlg.ShowDialog() == true)
    {
        textBoxSatelliteFolder.Text = dlg.SelectedPath;
        SaveFile(textBoxSatelliteFolder.Text, "satellitepath.txt");
    }
}

3. 修改构造函数的加载逻辑

直接将读取到的内容赋值给文本框的Text属性:

public MainWindow()
{
    InitializeComponent();
    textBoxRadarFolder.Text = LoadFile("radarpath.txt");
    textBoxSatelliteFolder.Text = LoadFile("satellitepath.txt");
}
可选优化

如果后续程序安装到C盘系统目录时出现保存失败的问题,可以将配置文件存储到当前用户的应用数据目录,替换获取根目录的逻辑即可:

// 替换原来获取applicationPath的代码
string appDataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "你的程序名称");
Directory.CreateDirectory(appDataDir); // 不存在则自动创建目录

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:48:03