【问题标题】:OpenFileDialog path issueOpenFileDialog 路径问题
【发布时间】:2012-07-16 11:46:19
【问题描述】:

我有一个 OpenFileDialog,当用户第一次使用应用程序时单击“浏览”时,它应该打开一个特定的路径,比如 %ProgramData%。 对于所有连续的术语,它应该打开最后使用的文件夹。

我试过了:

        OpenFileDialog ofd = new OpenFileDialog();
        ofd.InitialDirectory = "C:\ProgramData";
        ofd.RestoreDirectory = true;
        ofd.FileName = "";
        DialogResult dr = ofd.ShowDialog();

这里的问题是,它每次都会打开“C:\ProgramData”,即使我在查找所需文件时更改了路径。 是否有我应该设置的特定属性,或者我必须以编程方式跟踪 OpenFileDialog 的使用情况并相应地设置路径?

【问题讨论】:

  • 第一次是什么意思?应用程序加载后第一次使用或第一次使用应用程序。
  • 这是用户第一次使用该应用程序。抱歉不清楚。
  • 它每次都会打开“C:\ProgramData”,因为你用 InitialDirectory 告诉过。

标签: c# .net winforms mmc


【解决方案1】:

试试这个:

您在单击按钮时将初始目录重置为 C:\ProgramData

public partial class Form1 : Form
    {
           OpenFileDialog ofd = new OpenFileDialog();

        public Form1()
        {
            InitializeComponent();
            ofd.InitialDirectory = "C:\\ProgramData";
        }    
        private void button1_Click(object sender, EventArgs e)
        {                     
          DialogResult dr = ofd.ShowDialog();
          ofd.InitialDirectory = null;   
        }    
    }

【讨论】:

  • 你发现了问题,我每次都在重置初始目录。我稍微更改了您的代码,它终于对我有用。谢谢。
【解决方案2】:

做这样的事情:

// save your current directory  
string currentDirectory = Environment.CurrentDirectory;  

// create an OpenFileDialog and set RestoreCurrentDirectory to false.   
OpenFileDialog ofd = new OpenFileDialog();  
ofd.RestoreCurrentDirectory = false;  
ofd.ShowDialog();  

// save the selected directory locally.   
string selectedDirectory = Environment.CurrentDirectory;  // OpenFileDialog changed this value.   
Environment.CurrentDirectory = currentDirectory; // reset the property with the first value.   

// next time you open an OpenFileDialog, set the InitialDirectory property  
OpenFileDialog ofd2 = new OpenFileDialog();  
ofd.InitialDirectory = selectedDirectory; // set the InitialDirectory to what it was last time an OpenFileDialog was opened.   
ofd.ShowDialog(); 

RestoreDirectory 属性确保 Environment.CurrentDirectory 中的值将在 OpenFileDialog 关闭之前重置。如果 RestoreDirectory 设置为 false,则 Environment.CurrentDirectory 将设置为 OpenFileDialog 上次打开的目录。

【讨论】:

  • 可能它会起作用,我选择用 Vinod 的想法来实现(检查选择的答案)。我必须对现有代码进行简单的更改。感谢您的宝贵时间,这很有帮助。
  • 我刚刚在 Win7 64 和 VS 2010 上做了一些测试,据我所知,OpenFileDialog 对 Environment.CurrentDirectory 完全没有影响。
【解决方案3】:

我认为你读错了RestoreDirectory 属性。实际上,它会在对话框关闭后将目录恢复为默认值。与您想要做的正好相反。

另请查看:OpenFileDialog RestoreDirectory as no effect if Multiselect is set to true

【讨论】:

    【解决方案4】:

    简单地说,

    设置FileDialog.RestoreDirectory 属性true。重新打开文件对话框时,它会定位到最后一个目录。

    示例:

    ofd . RestoreDirectory = true;
    

    【讨论】:

    • 不会因为 OpenFileDialog.RestoreDirectory 没有实现而工作
    • 这是当你将鼠标悬停在属性上时 VS 告诉你的。不知道为什么这么说,这似乎是真的,因为即使属性值发生了变化,我也没有看到任何变化
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 2014-03-05
    • 2023-03-02
    • 1970-01-01
    • 2011-08-31
    • 2023-03-23
    相关资源
    最近更新 更多