9

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?

4

5 回答 5

2

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...

于 2009-08-11T08:55:14.373 回答
0

For clarification - By common desktop do you mean C:\Documents and Settings\All Users\Desktop?

If yes, this is an ugly hack -

Dim c As String = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
Dim comDesktop As String = c.Substring(0, c.LastIndexOf("\")) + "\Desktop"
于 2009-08-11T09:01:01.990 回答
0

You can use Windows Script Host - WshShell.SpecialFolders

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

于 2009-08-11T09:02:04.810 回答
0

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

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell 文件夹,通用桌面

于 2009-08-11T09:11:10.207 回答
0

First, add a reference to "Windows Script Host Object Model". You'll find this in the COM tab of the "Add References" dialog.

using IWshRuntimeLibrary;

object commonUserDesktop = "AllUsersDesktop";
WshShell shell = new WshShellClass();
string commonPath = shell.SpecialFolders.Item(ref commonUserDesktop).ToString();
于 2009-08-11T09:07:32.163 回答