Created
July 2, 2018 15:15
-
-
Save ksasao/a452adc527ff5b96ac3507deb7577414 to your computer and use it in GitHub Desktop.
Directory.GetLogicalDrives() does not return network drives when a process is running with administrator privileges. This code returns all logical drives including network drives whether it runs in administrator or not.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Collections.Generic; | |
| using System.IO; | |
| using System.Runtime.InteropServices; | |
| using System.Text; | |
| namespace Mpga | |
| { | |
| /// <summary> | |
| /// Directory.GetLogicalDrives() does not return network drives when a process | |
| /// is running with administrator privileges. | |
| /// | |
| /// This code returns all logical drives including network drives | |
| /// whether it runs in administrator or not. | |
| /// </summary> | |
| public static class DirectoryEx | |
| { | |
| [DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)] | |
| public static extern int WNetGetConnection( | |
| [MarshalAs(UnmanagedType.LPTStr)] string localName, | |
| [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName, | |
| ref int length); | |
| public static string[] GetLogicalDrives() | |
| { | |
| List<string> list = new List<string>(); | |
| list.AddRange(Directory.GetLogicalDrives()); | |
| StringBuilder sb = new StringBuilder(); | |
| foreach (var e in list) | |
| { | |
| sb.Append(e[0]); | |
| } | |
| string driveLetters = sb.ToString().ToUpper(); | |
| for (char c = 'C'; c <= 'Z'; c++) | |
| { | |
| if (driveLetters.IndexOf(c) < 0) | |
| { | |
| var uncPath = new StringBuilder(512); | |
| var len = uncPath.Capacity; | |
| WNetGetConnection($"{c}:", uncPath, ref len); | |
| if (uncPath.Length > 0) | |
| { | |
| list.Add($"{c}:\\"); | |
| } | |
| } | |
| } | |
| list.Sort(); | |
| return list.ToArray(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment