Click here to Skip to main content
15,886,258 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Since the HomeDrive is not always 'C' but can be 'D' or 'Y' or something totally unexpected how would I retrieve the System's Drive correctly?
There exists an environment variable %SystemDrive%, but I'm not sure if it is on every OS available. Messing with the Environment Variables is in generally not so good style. Some variables might be not there on another computer by a reason. So what else would I do to detect it correctly?
Posted

1 solution

There are a couple of options discussed here[^]

From the link above...
C#
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint GetWindowsDirectory(StringBuilder lpBuffer, uint uSize);

public string WindowsDirectory()
{
    uint size = 0;
    size = GetWindowsDirectory(null, size);

    StringBuilder sb = new StringBuilder((int)size);
    GetWindowsDirectory(sb, size);

    return sb.ToString();
}
then
var drive = System.IO.Path.GetPathRoot(WindowsDirectory());
will give you the drive it is installed on.
 
Share this answer
 
v2
Comments
CHill60 25-Feb-15 10:31am    
By "System" directory I took you to mean the Windows directory (most people would have). What do you mean by "System Directory"?? It's a very unusual situation to have all of windows on one drive and the windows system folder on the other - not sure that would work well
Richard Deeming 25-Feb-15 10:58am    
No need for the P/Invoke - just use:
Environmment.GetFolderPath(Environment.SpecialFolder.Windows)
CHill60 25-Feb-15 11:10am    
True - that was one of the suggestions on the link I supplied. I just grabbed the one that had been accepted as the answer - could have saved myself some cut&paste time if I'd gone for the simpler one :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900