Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the CommonOpenFileDialog's InitialDirectory to be the user's MyDocuments path, instead of Libraries\Documents?

Tags:

c#

wpf

I'm using the CommonOpenFileDialog in the Windows API Code Pack as a folder picker dialog. I'm setting the InitialDirectory property to Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments). However, when I display the dialog, the path in the address bar is Libraries\Documents (not C:\users\craig\my documents as I'd expect). Additionally, if I just press the Select Folder button, I get a dialog saying that 'You've selected a library. Please choose a folder instead.'

Does someone know why my file path is being ignored, in favor of 'libraries\documents'? More importantly, how can I get the dialog to respect the InitialDirectory value I passed in?

The code I'm using for the dialog is:

if (CommonFileDialog.IsPlatformSupported)
{
    var folderSelectorDialog = new CommonOpenFileDialog();
    folderSelectorDialog.EnsureReadOnly = true;
    folderSelectorDialog.IsFolderPicker = true;
    folderSelectorDialog.AllowNonFileSystemItems = false;
    folderSelectorDialog.Multiselect = false;
    folderSelectorDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    folderSelectorDialog.Title = "Project Location";

    if (folderSelectorDialog.ShowDialog() == CommonFileDialogResult.Ok)
    {
      ShellContainer shellContainer = null;

      try
      {
        // Try to get a valid selected item
        shellContainer = folderSelectorDialog.FileAsShellObject as ShellContainer;
      }
      catch
      {
        MessageBox.Show("Could not create a ShellObject from the selected item");
      }

      FilePath = shellContainer != null ? shellContainer.ParsingName : string.Empty;
    }
}

Thanks,

-Craig

like image 482
Craig Avatar asked Nov 06 '22 00:11

Craig


1 Answers

First of all, I'm sorry it took me so long to understand your question.

The message I see is when I try this is:

Cannot operate on 'Libraries\Documents' because it is not part of the file system.

There's not much more to say. A library is a virtual folder that is an amalgamation of various different real folders.

There's no real way to avoid this error. You have asked the dialog to return a folder and the user has not selected a folder. The dialog therefore cannot fulfil its part of the deal.

If you descend further into the folder structure, into real folders, then the dialog will return you a real value.

like image 73
David Heffernan Avatar answered Nov 14 '22 00:11

David Heffernan