代码之家  ›  专栏  ›  技术社区  ›  OregonGhost

在.NET中获取公用桌面路径

  •  8
  • OregonGhost  · 技术社区  · 15 年前

    我需要将文件存储到Windows上的公共桌面。该应用程序对于一台专用PC(设备准备)来说是一个非常特殊的应用程序,因此非技术用户很容易找到和修改配置文件。现在我们切换到一个域,因为不同的人(具有不同的帐户)应该使用该软件,所以它必须在一个共同的地方,每个用户都可以看到。所以请不要问为什么它在桌面上;)

    以前,我只是用 Environment.GetFolderPath(Environment.SpecialFolder.Desktop) . 在 SpecialFolder 枚举,但普通桌面似乎不存在。我是错过了什么,还是必须求助于 SHGetSpecialFolderPath 具有 CSIDL_COMMON_DESKTOPDIRECTORY ?

    5 回复  |  直到 10 年前
        1
  •  2
  •   Thomas Levesque    15 年前

    我想你必须使用 SHGetSpecialFolderPath api,因为“commondesktopdirectory”没有枚举值。不能显式使用 CSIDL_COMMON_DESKTOPDIRECTORY 把它铸造成 Environment.SpecialFolder ,因为 GetFolderPath 方法检查该值是否在枚举中定义。这是 获取文件路径 方法(来自反射镜):

    public static string GetFolderPath(SpecialFolder folder)
    {
        if (!Enum.IsDefined(typeof(SpecialFolder), folder))
        {
            throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, GetResourceString("Arg_EnumIllegalVal"), new object[] { (int) folder }));
        }
        StringBuilder lpszPath = new StringBuilder(260);
        Win32Native.SHGetFolderPath(IntPtr.Zero, (int) folder, IntPtr.Zero, 0, lpszPath);
        string path = lpszPath.ToString();
        new FileIOPermission(FileIOPermissionAccess.PathDiscovery, path).Demand();
        return path;
    }
    

    所以你可以很容易地复制和调整你需要的部分…

        2
  •  0
  •   Anonymous    15 年前

    澄清-你的意思是C:\documents and settings\all users\desktop?

    如果是,这是一个丑陋的黑客-

    Dim c As String = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
    Dim comDesktop As String = c.Substring(0, c.LastIndexOf("\")) + "\Desktop"
    
        3
  •  0
  •   Bogdan_Ch    15 年前

    您可以使用Windows脚本宿主-wshshell.specialfolders

    http://msdn.microsoft.com/en-us/library/0ea7b5xe(VS.85).aspx

        4
  •  0
  •   Jim    15 年前

    首先,添加对“Windows脚本宿主对象模型”的引用。您可以在“添加引用”对话框的“COM”选项卡中找到它。

    using IWshRuntimeLibrary;
    
    object commonUserDesktop = "AllUsersDesktop";
    WshShell shell = new WshShellClass();
    string commonPath = shell.SpecialFolders.Item(ref commonUserDesktop).ToString();
    
        5
  •  0
  •   Bogdan_Ch    15 年前

    另一种方法(是的,它也很难看,可能只能在Windows XP上工作,而不能在Vista上工作) 从注册表中读取值

    hkey_local_machine\software\microsoft\windows\currentversion\explorer\shell文件夹,公用桌面