如果驅動程序爲「COM2」返回意外的「文件類型」,則可能導致此錯誤。
嘗試使用p/Invoking GetFileType,我相信您會看到該模式。它必須是FILE_TYPE_CHAR
或FILE_TYPE_UNKNOWN
否則SerialPort
將拋出該異常。
class Program
{
static void Main(string[] args)
{
string portName = @"COM2";
IntPtr handle = CreateFile(portName, 0, 0, IntPtr.Zero, 3, 0x80, IntPtr.Zero);
if (handle == (IntPtr)(-1))
{
Console.WriteLine("Could not open " + portName + ": " + new Win32Exception().Message);
Console.ReadKey();
return;
}
FileType type = GetFileType(handle);
Console.WriteLine("File " + portName + " reports its type as: " + type);
Console.ReadKey();
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
public static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr SecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll")]
static extern FileType GetFileType(IntPtr hFile);
enum FileType : uint
{
UNKNOWN = 0x0000,
DISK = 0x0001,
CHAR = 0x0002,
PIPE = 0x0003,
REMOTE = 0x8000,
}
}
另請參閱MSDN論壇上的this thread。
司機麻煩,他們往往是可怕的。查找製造商的更新,如果無法修復,請將設備垃圾。 – 2010-07-06 13:34:48
我找到了解決方案。不是一個漂亮的,但在一些PC上的USB驅動程序只是不太好。 那麼我最後只是嘗試打開端口十次,每次嘗試之間有500毫秒的延遲。我認爲漏洞問題是getPortNames()函數之間的延遲監聽端口可用,直到實際上可以打開端口。 – JakobJ 2010-07-08 09:33:21
男人,這是可惡的。我知道你的痛苦。我的家用電腦使用依賴USB連接的顯示器設置。任何時候系統失去電力,我必須花費10分鐘在我的膝蓋上反覆重新插入USB連接直到需要並且我可以有視頻。 USB需要工作。 – 2010-07-08 17:43:17