Search code examples
.netwindowswindows-shell

Get common desktop path in .NET


I need to store files into the common desktop on Windows. The application is a very special application for exactly one special PC (device preparation), so it had to be easy for non-techie users to find and modify the configuration file. Now we switched to a domain, and because different people (with different accounts) should use the software, it has to be in a common place, seen by every user. So please don't ask why it's on the desktop ;)

Previously, I just used Environment.GetFolderPath(Environment.SpecialFolder.Desktop). There are several of the common folders in the SpecialFolder enumeration, but the common desktop seems not to be there. Am I missing something, or do I have to p/invoke SHGetSpecialFolderPath with CSIDL_COMMON_DESKTOPDIRECTORY?


Solution

  • I think you have to use the SHGetSpecialFolderPath API, since there is no enum value for "CommonDesktopDirectory". You can't explicitly use the value of CSIDL_COMMON_DESKTOPDIRECTORY and cast it to Environment.SpecialFolder, because the GetFolderPath method checks that the value is defined in the enum. Here's the code of the GetFolderPath method (from Reflector) :

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

    So you can easily copy and adapt the part that you need...