3

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

我试过:

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

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

4

4 回答 4

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 上次打开的目录。

于 2012-07-16T11:57:16.900 回答
2

试试这个:

您正在单击按钮时将初始目录重置为 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;   
        }    
    }
于 2012-07-16T12:01:53.297 回答
1

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

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

于 2012-07-16T11:55:43.820 回答
-1

简单地,

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

例子 :

ofd . RestoreDirectory = true;
于 2012-07-16T11:51:04.863 回答