Opening Devices in C# -- Why am I getting "Illegal Characters in Path" exceptions?

K

Karl Koscher

I'm trying to communicate with a USB device using C#. I'm able to determine
the device path using P/Invoke and SetupDiGetClassDevs,
SetupDiEnumDeviceInterfaces, and SetupDiGetDeviceInterfaceDetail, but I
can't open the device using File.Open. I get the following error:

An unhandled exception of type 'System.ArgumentException' occurred in
mscorlib.dll

Additional information: Illegal characters in path.

The path name is
\\?\usb#vid_0da0&pid_1000#6&2d560690&0&1#{6d2f6bb8-73e9-4283-a478-b6b493962df9}

The path name is determined by code, so it shouldn't be a problem with not
properly escaping the slashes. Even double- and triple-escaping the slashes
doesn't do any good. There aren't any hidden null characters in the string
either.

Dumping System.IO.Path.InvalidChars produces: (non-printable chars removed)

System.IO.Path.InvalidPathChars
{Length=0xf}
[0x0]: 0x22 '"'
[0x1]: 0x3c '<'
[0x2]: 0x3e '>'
[0x3]: 0x7c '|'
[0x4]: 0x0 ''
[0x5]: 0x8
[0x6]: 0x10
[0x7]: 0x11
[0x8]: 0x12
[0x9]: 0x14
[0xa]: 0x15
[0xb]: 0x16
[0xc]: 0x17
[0xd]: 0x18

Any ideas why .net doesn't like this? Looking at the stack trace, my hunch
is that it's trying to split the file name into the directory and file name
parts, and \\?\ isn't a "real" directory. Is there a way to open this device
without resorting to using P/Invoke and CreateFile/ReadFile/WriteFile?

Thanks,
Karl Koscher
 
W

Willy Denoyette [MVP]

Is there a way to open this device
without resorting to using P/Invoke and CreateFile/ReadFile/WriteFile?
No, the FCL are designed to open logical files only. So you will have to
PInvoke CreateFile and use the file handle returned to access the device
using the FileStream class.

Willy.
 
K

Karl Koscher

No, the FCL are designed to open logical files only. So you will have to
PInvoke CreateFile and use the file handle returned to access the device
using the FileStream class.

Thanks! I wasn't aware that FileStream could use native file handles. It
works fine now.

- Karl
 
Top