Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the Initial Directory on an OpenFileDIalog to the users `Downloads` folder in C#

Ok so I have an OpenFileDialog and I want to set the initial directory to the users 'Download' folder. This is an internal application and, therefore, I am sure that the user will be using Windows 7.

var ofd = new OpenFileDialog();

//This doesn't work
ofd.InitialDirectory =
    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Downloads");

//This doesn't work either
ofd.InitialDirectory = @"%USERPROFILE%\Downloads";

ofd.Filter = "Zip Files|*.zip";

ofd.ShowDialog();

txtFooBar.Text = ofd.FileName;

I have tried the above so far and neither work. No Exception is thrown, it just doesn't set the initial directory to the downloads folder.

Where am I going wrong?

Thanks

like image 864
JMK Avatar asked Mar 18 '12 17:03

JMK


People also ask

What is an initial directory?

The InitialDirectory property is typically set using one of the following sources: A path that was previously used in the program, perhaps retained from the last directory or file operation. A path read from a persistent source, such as an application setting, a Registry or a string resource in the application.


2 Answers

Maybe this could help: https://stackoverflow.com/a/1175250/333404

UPDATE:

Works for me: https://stackoverflow.com/a/3795159/333404

  private void Button_Click_1(object sender, RoutedEventArgs e) {
            var ofd = new OpenFileDialog();
            ofd.InitialDirectory = GetDownloadsPath();
            ofd.Filter = "Zip Files|*.zip";
            ofd.ShowDialog();
        }

        public static string GetDownloadsPath() {
            string path = null;
            if (Environment.OSVersion.Version.Major >= 6) {
                IntPtr pathPtr;
                int hr = SHGetKnownFolderPath(ref FolderDownloads, 0, IntPtr.Zero, out pathPtr);
                if (hr == 0) {
                    path = Marshal.PtrToStringUni(pathPtr);
                    Marshal.FreeCoTaskMem(pathPtr);
                    return path;
                }
            }
            path = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
            path = Path.Combine(path, "Downloads");
            return path;
        }

        private static Guid FolderDownloads = new Guid("374DE290-123F-4565-9164-39C4925E467B");
        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        private static extern int SHGetKnownFolderPath(ref Guid id, int flags, IntPtr token, out IntPtr path);
like image 156
Robar Avatar answered Oct 01 '22 11:10

Robar


I was able to use the environment to call directly but I had to add ToString() to the end. It didn't work until I added it.

saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
like image 29
Tim Melton Avatar answered Oct 01 '22 12:10

Tim Melton