Sunday, February 04, 2007

Access common windows folders from C#

I interested to get desktop and programs folder from C# application to create some shortcuts there. .NET allows it in following way:

Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Environment.GetFolderPath(Environment.SpecialFolder.Programs);

But results are directories for the current user, like

c:\document And Settings\LastDon\Destkop.

However I want to place shortcuts for all users, for profile ALLUSERS.
So, I found registry key

HKEY_LOCAL_MACHINE\SOFTWARE\microsoft\windows\currentversion\explorer\shell folders

Not too happy - Windows 2003 is not using this key, and anyway, it is not recommended by microsoft.
So, I come to solution by using API Shell32.dll:



[DllImport("Shell32.DLL")]
public static extern int SHGetSpecialFolderLocation(
IntPtr hwndOwner, int nFolder, out IntPtr ppidl);

[DllImport("Shell32.DLL")]
public static extern int SHGetPathFromIDList(
IntPtr pidl, StringBuilder Path);

const int CSIDL_COMMON_PROGRAMS = 23;
const int CSIDL_COMMON_STARTUP = 24;
const int CSIDL_COMMON_DESKTOPDIRECTORY = 25;

private string GetSpecialFolder(int folderType)
{
IntPtr pResultList;
IntPtr handlePtr = new IntPtr(0);
int result =SHGetSpecialFolderLocation(handlePtr, folderType, out pResultList);
if (result < 0)
{
return null;
}
StringBuilder sb = new StringBuilder (500);
result = SHGetPathFromIDList(pResultList, sb);
if (result == 0) // boolean result
{
return null;
}
return sb.ToString();
}




Get destkop path:
GetSpecialFolder(CSIDL_COMMON_DESKTOPDIRECTORY);
Get programs path:
GetSpecialFolder(CSIDL_COMMON_PROGRAMS);

Following microsoft article helped me to solve it out
http://support.microsoft.com/kb/306285

No comments: