Search code examples
c#.netopenfiledialogonedrivedocuments

My Documents Path Re-directing to OneDrive Path


I'll Start with the very simple code



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

What i'm trying to do is use the .Net OpenFileDialog. and set the InitialDirectory to the user who is running the application's My Documents folder.

The code sets the path of Initial Directory to: C:\Users\Aaron\Documents, which is the test users My Documents Directory.

When I run the code, the OpenFileDialog is actually opening in directory: C:\Users\Aaron\OneDrive\Documents. Which is the One Drive location.

This is happening on both my machines, but not my friends machine.

Why is the OneDrive Documents Folder Opening when this is not the Path set to OpenFIleDialog.InitialDirectory ?

EDIT: I should probably update this. The following day I ran my project again and the issue was no longer happening. I did not change my code either. It must have been a fluke scenario.


Solution

  • The dialog box should not be opening "OneDrive\Documents". It might be that you have redirected your "Documents" folder to OneDrive's, but because you've more or less hard coded the path, that seems unlikely.

    This is why in general you should never assume that the user's documents are located in C:\Users\{USERNAME}\Documents. It can be changed by the user or group policy and is not guaranteed to be there in future versions of Windows.

    To find the user's "My Documents" folder (or "Documents" on Vista and up) use this:

    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    

    So your code would be:

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