我的文档路径重定向到 OneDrive 路径

ayy*_*mao 5 .net c# documents openfiledialog onedrive

我将从非常简单的代码开始



    string fileName; // filename of file            

    // get the filename
    using (OpenFileDialog openFileDialog = new OpenFileDialog()) {
          openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
          openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
          openFileDialog.FilterIndex = 1;
          openFileDialog.ShowDialog();
          fileName = openFileDialog.FileName;
    }

Run Code Online (Sandbox Code Playgroud)

我想做的是使用.Net OpenFileDialog.并将其设置InitialDirectory为运行应用程序的“我的文档”文件夹的用户。

代码将初始目录的路径设置为:C:\Users\Aaron\Documents,即测试用户的我的文档目录。

当我运行代码时,OpenFileDialog实际上是在目录中打开的:C:\Users\Aaron\OneDrive\Documents。这是 One Drive 位置。

我的两台机器上都发生这种情况,但我朋友的机器上却没有。

当路径未设置为 时,为什么 OneDrive 文档文件夹会打开OpenFIleDialog.InitialDirectory

编辑:我可能应该更新这个。第二天,我再次运行我的项目,问题不再发生。我也没有更改我的代码。这一定是一个侥幸的情况。

PC *_*ite 1

该对话框不应打开“OneDrive\Documents”。您可能已将“文档”文件夹重定向到 OneDrive,但由于您或多或少对路径进行了硬编码,因此这似乎不太可能。

这就是为什么通常您不应该假设用户的文档位于C:\Users\{USERNAME}\Documents. 它可以由用户或组策略更改,并且不保证在未来版本的 Windows 中存在。

要查找用户的“我的文档”文件夹(或 Vista 及更高版本上的“文档”),请使用以下命令:

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Run Code Online (Sandbox Code Playgroud)

所以你的代码将是:

string fileName; // filename of file            

// get the filename
using (OpenFileDialog openFileDialog = new OpenFileDialog()) {
      openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
      openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
      openFileDialog.FilterIndex = 1;
      openFileDialog.ShowDialog();
      fileName = openFileDialog.FileName;
}
Run Code Online (Sandbox Code Playgroud)

  • 这使代码变得更好,但没有解决最初的问题“为什么 OneDrive 文档文件夹打开?” (4认同)