好的,我有一个OpenFileDialog,我想将初始目录设置为用户的'Download'文件夹。这是一个内部应用程序,因此,我确信用户将使用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;
到目前为止,我已经尝试了上述内容,但都没有工作。没有抛出异常,它只是没有将初始目录设置为下载文件夹。
我哪里错了?
由于
答案 0 :(得分:5)
也许这可以提供帮助:https://stackoverflow.com/a/1175250/333404
<强>更新强>:
适合我: 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);
答案 1 :(得分:4)
我能够使用环境直接调用,但我必须添加ToString()
到最后。直到我添加它才行。
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop).ToString();
答案 2 :(得分:0)
试试这个
ofd.InitialDirectory = @"%USERPROFILE%\My Documents\Downloads";
答案 3 :(得分:0)
下载文件夹有一个本地化的名称,无论如何,假设一个众所周知的文件夹的特定相对位置(即使它有详细记录)也不是一个好主意,因为它可能会被用户设置更改太
运行不幸SpecialFolder
枚举不包含每个已知文件夹,因此您必须使用一点互操作,请参阅MSDN。在该页面中,我们可以找到full list of known folders,您要查找的内容是 FOLDERID_Downloads ,因为SHGetKnownFolderPath函数需要GUID,您必须声明某个常量。您的代码将是这样的:
static class ShellHelpers
{
public static string GetDownloadsFolder()
{
string path;
int result = SHGetKnownFolderPath(FOLDERID_Downloads, 0, IntPtr.Zero, out path);
if (result != NOERROR)
Marshal.ThrowExceptionForHR(result); // You may fallback to another method or folder
return path;
}
private static readonly Guid FOLDERID_Downloads = new Guid("374DE290-123F-4565-9164-39C4925E467B");
private static readonly int NOERROR = 0;
[DllImport("shell32.dll", CharSet=CharSet.Unicode)]
private static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out string pszPath);
}
请注意您可以使用您喜欢的P / Invoke签名(有人使用StringBuilder,其他人使用IntPtr)。