Mapping DOS Device

When trying to work out how to map an LPT1 port to file so I could capture the output print jobs I had a heck of a time of it. Then I found this code on Stack Overflow which showed how to map a drive to another path. I only had to tweak it to remove the “:” at the end of the device as the LPT1 is just “LPT1”, not “LPT1:”. Also changed the input from a character, which is drive letters, to a string so it would accept “LPT1”.

    public static class Subst {

        // Redirect a device to a path
        // MapDrive("z:","c:\temp\zdrive\")
        // MapDrive("LPT1","c:\temp\printer\file.txt")
        // Console.WriteLine("LPT1 mapped to:"+Subst.GetDriveMapping("lpt1"));

        public static void MapDrive(string device, string path) 
        {
            if (!DefineDosDevice(0, devName(device), path))
                throw new Win32Exception();
        }

        public static void UnmapDrive(string device) 
        {
            if (!DefineDosDevice(2, devName(device), null))
                throw new Win32Exception();
        }

        public static string GetDriveMapping(string device) 
        {
            var sb = new StringBuilder(259);
            if (QueryDosDevice(devName(device), sb, sb.Capacity) == 0) 
            {
                // Return empty string if the drive is not mapped
                int err = Marshal.GetLastWin32Error();
                if (err == 2) return "";
                throw new Win32Exception();
            }
            return sb.ToString().Substring(4);
        }

        private static string devName(string device) 
        {
            return device.ToUpper();
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool DefineDosDevice(int flags, string devname, string path);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern int QueryDosDevice(string devname, StringBuilder buffer, int bufSize);
    }
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *