用try吧
if(!com.IsOpen)
{
    //设置属性    try
    {
        com.Open();
    }    catch(Exception)
    {
       com.Close();
       com.Dispose();
    }
}

解决方案 »

  1.   

    就是catch到了那个错误啊,InvalidOperation,说是端口没打开
      

  2.   


    代码:using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.IO.Ports;
    using System.IO;namespace SerialPortTest
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            SerialPort gpsPort = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
            private void button1_Click(object sender, EventArgs e)
            {
               
                //gpsPort.PortName = "COM4";
                //bool flag = gpsPort.IsOpen;
                //gpsPort.Open();
                //string[] str = new string[100];
                //str = SerialPort.GetPortNames();            try
                {
                    gpsPort.Open();
                }
                catch (System.Exception ex)
                {
                    FileStream fileStream = new FileStream("\\log.txt", FileMode.Create);
                    StreamWriter sw = new StreamWriter(fileStream, Encoding.Default);
                    sw.Write(ex.ToString());
                    sw.Close();
                }
                //int i;
                //byte[] buf = { 1, 2, 3 };
                //gpsPort.Write(buf, 0, buf.Length);
                gpsPort.Close();
            }
        }
    }
    log:
    System.IO.IOException: IOException
    位于 System.IO.Ports.SerialStream.WinIOError(Int32 errorCode, String str)
    位于 System.IO.Ports.SerialStream.WinIOError(Int32 err)
    位于 System.IO.Ports.SerialStream.CheckResult(Int32 err)
    位于 System.IO.Ports.SerialStream.InitializeDCB(Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Boolean discardNull)
    位于 System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeout, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNull, Byte parityReplace)
    位于 System.IO.Ports.SerialPort.Open()
    位于 SerialPortTest.Form1.button1_Click(Object sender, EventArgs e)
    位于 System.Windows.Forms.Control.OnClick(EventArgs e)
    位于 System.Windows.Forms.Button.OnClick(EventArgs e)
    位于 System.Windows.Forms.ButtonBase.WnProc(WM wm, Int32 wParam, Int32 lParam)
    位于 System.Windows.Forms.Control._InternalWnProc(WM wm, Int32 wParam, Int32 lParam)
    位于 Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain)
    位于 System.Windows.Forms.Application.Run(Form fm)
    位于 SerialPortTest.Program.Main()
      

  3.   

    为什么是COM4?难道你有4个COM端口?默认都是COM1
      

  4.   

    枚举过串口,有COM4,并且IsOpen属性都是false
      

  5.   

    检查下COM4是否真的存在的,或者有没别的程序占用了COM4
      

  6.   


    那看下有没别的程序使用了COM4,比如串口助手之类的
      

  7.   

    我考虑到是不是串口引用的dotNet库比如dll之类的出错了还是怎么着。是不是和CE上装cab有关,有在CE6平台上熟悉C#应用的吗,谢谢大家了。
      

  8.   


    好奇怪,我用你的代码试了下没问题的。
    你的错误日志没怎么看懂,取消catch,看看会报什么错还有种可能就是,你在自己的程序里别的地方打开了COM4但是没关闭
      

  9.   

    我这个不是在PC机器上,而是在我们的掌机上,系统式WINCE6.0另外COM4不是虚拟的,我们COM4上接gps,用C++能度到数据
      

  10.   

    并且是在机器上装了CAB包重启之后会有问题。另外好像还和SilVerLight组件相关
      

  11.   

    IOException 
    此端口处于无效状态。 - 或 - 尝试设置基础端口状态失败。例如,从此 SerialPort 对象传递的参数无效。
    既然C++能用,那端口无效状态基本可以排除。而且可以确定端口不是被占用了(因为被占用报的是InvalidOperationException)。所以应该是设置基础端口状态失败。设断点看看里面的属性值都对不对。跟C++的对比一下。
      

  12.   

    你C++ 能看见代码不
    SerialPort gpsPort = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
    这一段C++怎么写的
      

  13.   

    其实还没到open觉得里面的状态都不对了,您看看
      

  14.   

    你在open之前已经InvalidOperationException这个异常了,那应该是已经被占用了。
    要不就是其它程序占用的,要不就是这个程序本身占用的。
    很可能是你用C++调用的时候就占用了,没释放。重启一下机器,然后什么都别运行,就直接跑你的程序试试。
      

  15.   

    跟我以前做的一个项目好像啊 呵呵 COM4看看是否存在
    这是我的代码 希望能对你有所帮助SerialPort com;
            string port = "COM5";
            public void SerialPort_Open(string str)
            {
                try
                {
                    com = new SerialPort();
                    //USB端口串行波特率
                    com.BaudRate = 9600;
                    //设置通信端口,包括但不限于所有可用的COM端口
                    com.PortName = port;
                    //获取说设置每个字节的标准数据位长度
                    com.DataBits = 8;
                    if (com != null)
                    {
                        if (com.IsOpen)
                        {
                            com.Close();
                        }
                    }
                    //打开串口
                    com.Open();
                    Byte[] TxData = Write(str);
                    com.Write(TxData, 0, TxData.Length);
                    com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived);
                    com.Close();
                }
                catch (Exception ex)
                {
                    WriteLog("外部端口连接错误!" + ex.Message, ConfigurationManager.AppSettings["Error"]);
                    timer2.Enabled = false;
                    timer1.Enabled = false;
                    button18.Visible = false;
                    button2.Visible = true;
                    this.Text = "打印监控----已停止";
                    Statue = false;
                    if (connection.State == System.Data.ConnectionState.Broken || connection.State == System.Data.ConnectionState.Open)
                    {
                        connection.Close();
                    }
                }        }
      

  16.   

    http://bbs.csdn.net/topics/390428372?page=1#post-394226277
    另外一帖子,200分求助
      

  17.   

    不知道你是什么情况。
    我这个例子是在ce5下调用串口打印机的。
    http://download.csdn.net/detail/mjp1234airen4385/1664218
      

  18.   

    我这个不太一样,我开机第一次是可以的,但是安装一个cab包(CE的,和cab里面的东西没关系,因为即使安装从网上下载的UC浏览器的cab也不行),安装完重启后,所有串口无法使用
      

  19.   

    试试重装.NET,不知道是不是发生了冲突,也可以检查项目引用是否为原先的引用。
      

  20.   

    你看下你项目引用的System.dll的版本号和所在路径,先给我看下。然后可能的话你自己使用reflector打开该dll文件,查找那个 SerialStream类中的异常出处,我本地2.0和4.0两个版本的的dll都可以跟踪到那个System.IO.Ports.SerialStream.InitializeDCB方法,但是再往上找那个System.IO.Ports.SerialStream.CheckResult方法就不存在了,而且在InitializeDCB内部也未曾调用过CheckResult方法,由于WinIOError方法本身就是用来显示错误的一个方法包装,因此可以推断错误是由CheckResult引发的,也许我没安装.NET Compact Framework 的缘故,也许Compact的dll有所不同,你可以用此方法看看最终是哪里出的问题。
      

  21.   

    这还叫没关系,什么是有关系?
    初步怀疑是这个cab包里的什么类库或功能引起访问串口的类库失效了。
      

  22.   


    自己做一个空的cab包也会失败,空的cab包,里面就放一个txt之类的,这有影响吗
      

  23.   

    cab包里除了你自己的文件以外,还有一些系统必须的文件,会不会是这些文件造成影响。
      

  24.   

    你把你打包的cab包的inf文件打开看看,里面都使用了哪些类库。
    看看这些类库有没有对硬件资源访问的类库造成影响。
      

  25.   

    这是system.dll的版本:// Assembly Reference System 
    Version: 3.5.0.0 
    Name: System, Version=3.5.0.0, Culture=neutral, PublicKeyToken=969db8053d3322ac, Retargetable=Yes 但是反编译工具不太会用,我的程序要部署到掌机上,用的dll应该是掌机上的吧,不是pc上的吧
      

  26.   

    cab的inf:[Version]
    Signature="$Windows NT$"
    Provider="Thinta"
    CESignature="$Windows CE$"[CEStrings]
    AppName="CESetupCab"
    InstallDir=%CE1%\%AppName%[Strings]
    Manufacturer="Thinta"[CEDevice]
    VersionMin=4.0
    VersionMax=6.99
    BuildMax=0xE0000000[DefaultInstall]
    CEShortcuts=Shortcuts
    AddReg=RegKeys
    CopyFiles=Files.Common1,Files.Common2,Files.Common3,Files.Common4,Files.Common5
    CESetupDLL="CESetup.dll"[SourceDisksNames]
    1=,"Common1",,"C:\Users\friendy\Desktop\CESetup\CESetupCab\"
    2=,"Common2",,"C:\Users\friendy\Desktop\CESetup\CESetupCab\"
    3=,"Common3",,"C:\Users\friendy\Desktop\CESetup\CESetupCab\"
    4=,"Common4",,"C:\Users\friendy\Desktop\CESetup\CESetupCab\"
    5=,"Common5",,"C:\Users\friendy\Desktop\CESetup\CESetup\T31-SDK01 (ARMV4I)\Release\"[SourceDisksFiles]
    "T30Service.dll"=1
    "T30ServiceApiDll.dll"=2
    "T6DeviceDll.dll"=3
    "T6FactoryTest.exe"=4
    "CESetup.dll"=5[DestinationDirs]
    Shortcuts=0,%CE2%\Start Menu
    Files.Common1=0,"%CE2%"
    Files.Common2=0,"%CE2%"
    Files.Common3=0,"%CE2%"
    Files.Common4=0,"%InstallDir%"
    Files.Common5=0,"%InstallDir%"[Files.Common1]
    "T30Service.dll","T30Service.dll",,0[Files.Common2]
    "T30ServiceApiDll.dll","T30ServiceApiDll.dll",,0[Files.Common3]
    "T6DeviceDll.dll","T6DeviceDll.dll",,0[Files.Common4]
    "T6FactoryTest.exe","T6FactoryTest.exe",,0[Files.Common5]
    "CESetup.dll","CESetup.dll",,0
    [Shortcuts][RegKeys]
    "HKLM","ZZRD","CABVer","0x00000000","1.0.0.4"
      

  27.   

    这个是编译的时候选择好的,如果编译的时候选择的是PC上的dll,那么你的程序都不能到掌机上运行。因此你在调试的时候,程序就已经使用的是掌机上的dll了,而程序应该是在模拟器里被调试的。
      

  28.   

    [Files.Common3]
    "T6DeviceDll.dll","T6DeviceDll.dll",,0
    吧这个类库打开,看看里面有什么访问串口类的函数,也许是它造成的。
      

  29.   

    我同样也是做wince应用程序开发的,你的错误正是因为没有打开串口而引起的!
    你串口打开的参数类型过少,有些必须需要设置的,你没有设置。
      

  30.   

    楼主我也遇到同样的问题了 不过我是用VB.net用serialport 控件打开串口的读取的也是GPS数据 问题如果解决了 求教啊
      

  31.   

    遇到过这种问题.我用的是研华UNO-2074A嵌入式WINPE系统有4个物理串口,其中2个是接到PCI插槽上的后接的这2个我用SerialPort就无法打开.后来修改代码,不用SerialPort,改为调用WINDOWS API就好了.