SerialPort port.open “The port 'COM2' does not exist.”

前端 未结 2 827
太阳男子
太阳男子 2021-02-14 09:59

I\'m having a big problem with the SerialPort.Open();

I am communicating with an usb virtual com port (cdc), and it is listed as COM2.

It works fine

2条回答
  •  爱一瞬间的悲伤
    2021-02-14 10:40

    This error can be caused if the driver returns an unexpected "file type" for "COM2".

    Try p/Invoking GetFileType and I believe you'll see the pattern. It has to be FILE_TYPE_CHAR or FILE_TYPE_UNKNOWN or else SerialPort will throw that exception.

    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,
      }
    }
    

    Also see this thread on MSDN forums.

提交回复
热议问题