Created
March 31, 2021 07:09
-
-
Save vurdalakov/e41b1ed7718dd9b5c305cb341beeb546 to your computer and use it in GitHub Desktop.
Get list of MS-DOS devices and their mappings using QueryDosDevice function
This file contains 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
namespace Vurdalakov | |
{ | |
using System; | |
using System.Collections.Generic; | |
using System.Runtime.InteropServices; | |
using System.Text; | |
class Program | |
{ | |
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] | |
private static extern Int32 QueryDosDeviceW(String lpDeviceName, Char[] lpTargetPath, Int32 ucchMax); | |
static void Main(string[] args) | |
{ | |
var buffer = new Char[65536]; | |
// get list of all device names | |
var size = QueryDosDeviceW(null, buffer, buffer.Length - 1); | |
if (0 == size) | |
{ | |
Console.WriteLine($"QueryDosDeviceW failed with error {Marshal.GetLastWin32Error()}"); | |
return; | |
} | |
var deviceNames = ParseNullTerminatedString(buffer, 0, size); | |
Console.WriteLine($"--- {deviceNames.Count} devices:"); | |
// get device mappings | |
foreach (var deviceName in deviceNames) | |
{ | |
Console.Write(deviceName); | |
size = QueryDosDeviceW(deviceName, buffer, buffer.Length - 1); | |
if (0 == size) | |
{ | |
Console.WriteLine($"QueryDosDeviceW failed with error {Marshal.GetLastWin32Error()}"); | |
} | |
else | |
{ | |
var deviceMapings = ParseNullTerminatedString(buffer, 0, size); | |
if (deviceMapings.Count > 0) | |
{ | |
Console.Write($"\t{deviceMapings[0]}"); | |
} | |
Console.WriteLine(); | |
} | |
} | |
} | |
private static List<String> ParseNullTerminatedString(Char[] buffer, Int32 startIndex, Int32 length) | |
{ | |
var strings = new List<String>(); | |
var stringBuilder = new StringBuilder(); | |
for (var i = startIndex; i < startIndex + length; i++) | |
{ | |
if ('\0' == buffer[i]) | |
{ | |
if (0 == stringBuilder.Length) | |
{ | |
break; | |
} | |
strings.Add(stringBuilder.ToString()); | |
stringBuilder.Clear(); | |
} | |
else | |
{ | |
stringBuilder.Append(buffer[i]); | |
} | |
} | |
return strings; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment