C#基于控制台程序,一直获取串口数据的代码!谢谢!

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#基于控制台程序,一直获取串口数据的代码!谢谢!相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1

class Program

static void Main(string[] args)

object para = "";//传入GetData方法的参数
Timer timer = new Timer(new TimerCallback(GetData), para, 0, 1000);//定义并开启计时器,间隔1000ms
while (Console.ReadKey(true).Key != ConsoleKey.Escape) //按下Escape键退出

private static void GetData(object para)

///这里添加获取串口数据的代码


参考技术A 用timer,在timer中设定时间,通过线程方式每隔一段时间(可以设定很小的间隔时间)执行获取数据的操作追问

有没有类似的代码?

追答

你搜一下timer的用法,然后根据网上的例子套吧,我没写过但是看到过,很简单的,我总不能随便搜点代码给你粘上,你还是自己动手学习学习吧,加油啊

参考技术B 是控制台程序,又不是winform,哪里来的timer?你可以用一个死循环,然后里面跑线程,执行完成一次后sleep(一个时间),就OK了 参考技术C 开个定时器,实时从串口接收缓冲区读数据就可以了啊

(高分求助)怎么用C#语言实现串口通讯,需要程序,急!

调用API实现,最好是不用控件,需要源程序!急
总共就这么多分,希望高手能帮忙!谢谢

☆★○●◎◇◆□℃‰?■△▲※→←↑↓〓☆★○●◎◇◆□℃‰?■△▲※→←↑↓〓☆★○●◎◇◆□℃‰?■△▲※→←↑↓〓☆★○●◎◇◆□℃‰?■△▲※→←↑↓〓
通常,在C#中实现串口通信,我们有四种方法:

第一:通过MSCOMM控件这是最简单的,最方便的方法。可功能上很难做到控制自如,同时这个控件并不是系统本身所带,所以还得注册。可以访问
http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=320
一个外国人写的教程
第二:微软在.NET新推出了一个串口控件,基于.NET的P/Invoke调用方法实现,详细的可以访问微软网站
Serial Comm
Use P/Invoke to Develop a .NET Base Class Library for Serial Device Communications

http://msdn.microsoft.com/msdnmag/issues/02/10/netserialcomm/
第三:就是用第三方控件啦,可一般都要付费的,不太合实际,何况楼主不喜欢,不作考虑
第四:自己用API写串口通信,这样难度高点,但对于我们来说,可以方便实现自己想要的各种功能。

我们采用第四种方法来实现串口通信,用现成的已经封装好的类库,常见两个串口操作类是JustinIO和SerialStreamReader。介绍JustinIO的使用方法:

打开串口:

函数原型:public void Open()

说明:打开事先设置好的端口

示例:

using JustinIO;

static JustinIO.CommPort ss_port = new JustinIO.CommPort();
ss_port.PortNum = COM1; //端口号
ss_port.BaudRate = 19200; //串口通信波特率
ss_port.ByteSize = 8; //数据位
ss_port.Parity = 0; //奇偶校验
ss_port.StopBits = 1;//停止位
ss_port.ReadTimeout = 1000; //读超时
try

if (ss_port.Opened)

ss_port.Close();
ss_port.Open(); //打开串口

else

ss_port.Open();//打开串口

return true;

catch(Exception e)

MessageBox.Show("错误:" + e.Message);
return false;


写串口:

函数原型:public void Write(byte[] WriteBytes)

WriteBytes 就是你的写入的字节,注意,字符串要转换成字节数组才能进行通信

示例:

ss_port.Write(Encoding.ASCII.GetBytes("AT+CGMI\r")); //获取手机品牌

读串口:

函数原型:public byte[] Read(int NumBytes)

NumBytes 读入缓存数,注意读取来的是字节数组,要实际应用中要进行字符转换

示例:

string response = Encoding.ASCII.GetString(ss_port.Read(128)); //读取128个字节缓存

关闭串口:

函数原型:ss_port.Close()

示例:

ss_port.Close();

整合代码:
using System;
using System.Runtime.InteropServices;

namespace JustinIO
class CommPort

public int PortNum;
public int BaudRate;
public byte ByteSize;
public byte Parity; // 0-4=no,odd,even,mark,space
public byte StopBits; // 0,1,2 = 1, 1.5, 2
public int ReadTimeout;

//comm port win32 file handle
private int hComm = -1;

public bool Opened = false;

//win32 api constants
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
private const int OPEN_EXISTING = 3;
private const int INVALID_HANDLE_VALUE = -1;

[StructLayout(LayoutKind.Sequential)]
public struct DCB
//taken from c struct in platform sdk
public int DCBlength; // sizeof(DCB)
public int BaudRate; // current baud rate
/* these are the c struct bit fields, bit twiddle flag to set
public int fBinary; // binary mode, no EOF check
public int fParity; // enable parity checking
public int fOutxCtsFlow; // CTS output flow control
public int fOutxDsrFlow; // DSR output flow control
public int fDtrControl; // DTR flow control type
public int fDsrSensitivity; // DSR sensitivity
public int fTXContinueOnXoff; // XOFF continues Tx
public int fOutX; // XON/XOFF out flow control
public int fInX; // XON/XOFF in flow control
public int fErrorChar; // enable error replacement
public int fNull; // enable null stripping
public int fRtsControl; // RTS flow control
public int fAbortOnError; // abort on error
public int fDummy2; // reserved
*/
public uint flags;
public ushort wReserved; // not currently used
public ushort XonLim; // transmit XON threshold
public ushort XoffLim; // transmit XOFF threshold
public byte ByteSize; // number of bits/byte, 4-8
public byte Parity; // 0-4=no,odd,even,mark,space
public byte StopBits; // 0,1,2 = 1, 1.5, 2
public char XonChar; // Tx and Rx XON character
public char XoffChar; // Tx and Rx XOFF character
public char ErrorChar; // error replacement character
public char EofChar; // end of input character
public char EvtChar; // received event character
public ushort wReserved1; // reserved; do not use


[StructLayout(LayoutKind.Sequential)]
private struct COMMTIMEOUTS
public int ReadIntervalTimeout;
public int ReadTotalTimeoutMultiplier;
public int ReadTotalTimeoutConstant;
public int WriteTotalTimeoutMultiplier;
public int WriteTotalTimeoutConstant;


[StructLayout(LayoutKind.Sequential)]
private struct OVERLAPPED
public int Internal;
public int InternalHigh;
public int Offset;
public int OffsetHigh;
public int hEvent;


[DllImport("kernel32.dll")]
private static extern int CreateFile(
string lpFileName, // file name
uint dwDesiredAccess, // access mode
int dwShareMode, // share mode
int lpSecurityAttributes, // SD
int dwCreationDisposition, // how to create
int dwFlagsAndAttributes, // file attributes
int hTemplateFile // handle to template file
);
[DllImport("kernel32.dll")]
private static extern bool GetCommState(
int hFile, // handle to communications device
ref DCB lpDCB // device-control block
);
[DllImport("kernel32.dll")]
private static extern bool BuildCommDCB(
string lpDef, // device-control string
ref DCB lpDCB // device-control block
);
[DllImport("kernel32.dll")]
private static extern bool SetCommState(
int hFile, // handle to communications device
ref DCB lpDCB // device-control block
);
[DllImport("kernel32.dll")]
private static extern bool GetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);
[DllImport("kernel32.dll")]
private static extern bool SetCommTimeouts(
int hFile, // handle to comm device
ref COMMTIMEOUTS lpCommTimeouts // time-out values
);
[DllImport("kernel32.dll")]
private static extern bool ReadFile(
int hFile, // handle to file
byte[] lpBuffer, // data buffer
int nNumberOfBytesToRead, // number of bytes to read
ref int lpNumberOfBytesRead, // number of bytes read
ref OVERLAPPED lpOverlapped // overlapped buffer
);
[DllImport("kernel32.dll")]
private static extern bool WriteFile(
int hFile, // handle to file
byte[] lpBuffer, // data buffer
int nNumberOfBytesToWrite, // number of bytes to write
ref int lpNumberOfBytesWritten, // number of bytes written
ref OVERLAPPED lpOverlapped // overlapped buffer
);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(
int hObject // handle to object
);
[DllImport("kernel32.dll")]
private static extern uint GetLastError();

public void Open()

DCB dcbCommPort = new DCB();
COMMTIMEOUTS ctoCommPort = new COMMTIMEOUTS();

// OPEN THE COMM PORT.

hComm = CreateFile("COM" + PortNum ,GENERIC_READ | GENERIC_WRITE,0, 0,OPEN_EXISTING,0,0);

// IF THE PORT CANNOT BE OPENED, BAIL OUT.
if(hComm == INVALID_HANDLE_VALUE)
throw(new ApplicationException("Comm Port Can Not Be Opened"));


// SET THE COMM TIMEOUTS.

GetCommTimeouts(hComm,ref ctoCommPort);
ctoCommPort.ReadTotalTimeoutConstant = ReadTimeout;
ctoCommPort.ReadTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutMultiplier = 0;
ctoCommPort.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(hComm,ref ctoCommPort);

// SET BAUD RATE, PARITY, WORD SIZE, AND STOP BITS.
GetCommState(hComm, ref dcbCommPort);
dcbCommPort.BaudRate=BaudRate;
dcbCommPort.flags=0;
//dcb.fBinary=1;
dcbCommPort.flags|=1;
if (Parity>0)

//dcb.fParity=1
dcbCommPort.flags|=2;

dcbCommPort.Parity=Parity;
dcbCommPort.ByteSize=ByteSize;
dcbCommPort.StopBits=StopBits;
if (!SetCommState(hComm, ref dcbCommPort))

//uint ErrorNum=GetLastError();
throw(new ApplicationException("Comm Port Can Not Be Opened"));

//unremark to see if setting took correctly
//DCB dcbCommPort2 = new DCB();
//GetCommState(hComm, ref dcbCommPort2);
Opened = true;



public void Close()
if (hComm!=INVALID_HANDLE_VALUE)
CloseHandle(hComm);


public byte[] Read(int NumBytes)
byte[] BufBytes;
byte[] OutBytes;
BufBytes = new byte[NumBytes];
if (hComm!=INVALID_HANDLE_VALUE)
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesRead=0;
ReadFile(hComm,BufBytes,NumBytes,ref BytesRead,ref ovlCommPort);
OutBytes = new byte[BytesRead];
Array.Copy(BufBytes,OutBytes,BytesRead);

else
throw(new ApplicationException("Comm Port Not Open"));

return OutBytes;


public void Write(byte[] WriteBytes)
if (hComm!=INVALID_HANDLE_VALUE)
OVERLAPPED ovlCommPort = new OVERLAPPED();
int BytesWritten = 0;
WriteFile(hComm,WriteBytes,WriteBytes.Length,ref BytesWritten,ref ovlCommPort);

else
throw(new ApplicationException("Comm Port Not Open"));







由于篇幅,以及串口通信涉及内容广泛,我在这里只讲这些。
参考技术A //
//bool XmlTextReader.Read(): 读取流中下一个节点,当读完最后一个节点再次调用该方法该方法返回false
//XmlNodeType XmlTextReader.NodeType: 该属性返回当前节点的类型
// XmlNodeType.Element 元素节点
// XmlNodeType.EndElement 结尾元素节点
// XmlNodeType.XmlDeclaration 文档的第一个节点
// XmlNodeType.Text 文本节点
//bool XmlTextReader.HasAttributes: 当前节点有没有属性,返回true或false
//string XmlTextReader.Name: 返回当前节点的名称
//string XmlTextReader.Value: 返回当前节点的值
//string XmlTextReader.LocalName: 返回当前节点的本地名称
//string XmlTextReader.NamespaceURI: 返回当前节点的命名空间URI
//string XmlTextReader.Prefix: 返回当前节点的前缀
//bool XmlTextReader.MoveToNextAttribute(): 移动到当前节点的下一个属性
//---------------------------------------------------------------------------------------------------

namespace XMLReading

using System;
using System.Xml;
using System.Windows.Forms;
using System.ComponentModel;

/// <summary>
/// Xml文件读取器
/// </summary>

public class XmlReader : IDisposable

private string _xmlPath;
private const string _errMsg = "Error Occurred While Reading ";
private ListBox _listBox;
private XmlTextReader xmlTxtRd;

#region XmlReader 的构造器

public XmlReader()

this._xmlPath = string.Empty;
this._listBox = null;
this.xmlTxtRd = null;


/// <summary>
/// 构造器
/// </summary>
/// <param name="_xmlPath">xml文件绝对路径</param>
/// <param name="_listBox">列表框用于显示xml</param>

public XmlReader(string _xmlPath, ListBox _listBox)

this._xmlPath = _xmlPath;
this._listBox = _listBox;
this.xmlTxtRd = null;


#endregion
#region XmlReader 的资源释放方法

/// <summary>
/// 清理该对象所有正在使用的资源

/// </summary>

public void Dispose()

this.Dispose(true);
GC.SuppressFinalize(this);


/// <summary>
/// 释放该对象的实例变量
/// </summary>
/// <param name="disposing"></param>

protected virtual void Dispose(bool disposing)

if (!disposing)
return;
if (this.xmlTxtRd != null)

this.xmlTxtRd.Close();
this.xmlTxtRd = null;


if (this._xmlPath != null)

this._xmlPath = null;



#endregion
#region XmlReader 的属性

/// <summary>
/// 获取或设置列表框用于显示xml
/// </summary>

public ListBox listBox

get

return this._listBox;

set

this._listBox = value;



/// <summary>
/// 获取或设置xml文件的绝对路径
/// </summary>

public string xmlPath

get

return this._xmlPath;

set

this._xmlPath = value;



#endregion

/// <summary>
/// 遍历Xml文件
/// </summary>

public void EachXml()

this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);

try

while(xmlTxtRd.Read())

this._listBox.Items.Add(this.xmlTxtRd.Value);


catch(XmlException exp)

throw new XmlException(_errMsg + this._xmlPath + exp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();



/// <summary>
/// 读取Xml文件的节点类型
/// </summary>

public void ReadXmlByNodeType()

this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);

try

while(xmlTxtRd.Read())

this._listBox.Items.Add(this.xmlTxtRd.NodeType.ToString());


catch(XmlException exp)

throw new XmlException(_errMsg + this._xmlPath + exp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();



/// <summary>
/// 根据节点类型过滤Xml文档
/// </summary>
/// <param name="xmlNType">XmlNodeType 节点类型的数组</param>

public void FilterByNodeType(XmlNodeType[] xmlNType)

this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);
try

while(xmlTxtRd.Read())

for (int i = 0; i < xmlNType.Length; i++)

if (xmlTxtRd.NodeType == xmlNType[i])

this._listBox.Items.Add(xmlTxtRd.Name + " is Type " + xmlTxtRd.NodeType.ToString());




catch(XmlException exp)

throw new XmlException(_errMsg + this.xmlPath + exp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();



/// <summary>
/// 读取Xml文件的所有文本节点值

/// </summary>

public void ReadXmlTextValue()

this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);

try

while(xmlTxtRd.Read())

if (xmlTxtRd.NodeType == XmlNodeType.Text)

this._listBox.Items.Add(xmlTxtRd.Value);



catch(XmlException xmlExp)

throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();



/// <summary>
/// 读取Xml文件的属性
/// </summary>

public void ReadXmlAttributes()

this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);

try

while(xmlTxtRd.Read())

if (xmlTxtRd.NodeType == XmlNodeType.Element)

if (xmlTxtRd.HasAttributes)

this._listBox.Items.Add("The Element " + xmlTxtRd.Name + " has " + xmlTxtRd.AttributeCount + " Attributes");

this._listBox.Items.Add("The Attributes are:");

while(xmlTxtRd.MoveToNextAttribute())

this._listBox.Items.Add(xmlTxtRd.Name + " = " + xmlTxtRd.Value);


else

this._listBox.Items.Add("The Element " + xmlTxtRd.Name + " has no Attribute");

this._listBox.Items.Add("");



catch(XmlException xmlExp)

throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();



/// <summary>
/// 读取Xml文件的命名空间
/// </summary>

public void ReadXmlNamespace()

this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);
try

while(xmlTxtRd.Read())

if (xmlTxtRd.NodeType == XmlNodeType.Element && xmlTxtRd.Prefix != "")

this._listBox.Items.Add("The Prefix " + xmlTxtRd.Prefix + " is associated with namespace " + xmlTxtRd.NamespaceURI);

this._listBox.Items.Add("The Element with the local name " + xmlTxtRd.LocalName + " is associated with" + " the namespace " + xmlTxtRd.NamespaceURI);


if (xmlTxtRd.NodeType == XmlNodeType.Element && xmlTxtRd.HasAttributes)

while(xmlTxtRd.MoveToNextAttribute())

if (xmlTxtRd.Prefix != "")

this._listBox.Items.Add("The Prefix " + xmlTxtRd.Prefix + " is associated with namespace " + xmlTxtRd.NamespaceURI);

this._listBox.Items.Add("The Attribute with the local name " + xmlTxtRd.LocalName + " is associated with the namespace " + xmlTxtRd.NamespaceURI);






catch(XmlException xmlExp)

throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();



/// <summary>
/// 读取整个Xml文件
/// </summary>

public void ReadXml()

string attAndEle = string.Empty;
this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);

try

while(xmlTxtRd.Read())

if (xmlTxtRd.NodeType == XmlNodeType.XmlDeclaration)
this._listBox.Items.Add(string.Format("<?0 1 ?>",xmlTxtRd.Name,xmlTxtRd.Value));
else if (xmlTxtRd.NodeType == XmlNodeType.Element)

attAndEle = string.Format("<0 ",xmlTxtRd.Name);
if (xmlTxtRd.HasAttributes)

while(xmlTxtRd.MoveToNextAttribute())

attAndEle = attAndEle + string.Format("0='1' ",xmlTxtRd.Name,xmlTxtRd.Value);



attAndEle = attAndEle.Trim() + ">";
this._listBox.Items.Add(attAndEle);

else if (xmlTxtRd.NodeType == XmlNodeType.EndElement)
this._listBox.Items.Add(string.Format("</0>",xmlTxtRd.Name));
else if (xmlTxtRd.NodeType == XmlNodeType.Text)
this._listBox.Items.Add(xmlTxtRd.Value);


catch(XmlException xmlExp)

throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();





窗体代码如下:

namespace XMLReading



using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Xml;

public class Form1 : System.Windows.Forms.Form



private System.Windows.Forms.ListBox listBox1;

private System.Windows.Forms.Button button1;

private System.Windows.Forms.Button button2;

private System.Windows.Forms.Button button3;

private System.Windows.Forms.Button button4;

private System.Windows.Forms.Button button5;

private System.Windows.Forms.Button button6;

private System.Windows.Forms.Button button7;

private string xmlPath;

private XmlReader xRead;

/// <summary>

/// 必需的设计器变量。

/// </summary>

private System.ComponentModel.Container components = null;

public Form1()



InitializeComponent();



/// <summary>

/// 清理所有正在使用的资源。

/// </summary>

protected override void Dispose( bool disposing )



if( disposing )



if (components != null)



components.Dispose();





base.Dispose( disposing );



#region Windows 窗体设计器生成的代码

/// <summary>

/// 设计器支持所需的方法 - 不要使用代码编辑器修改

/// 此方法的内容。

/// </summary>

private void InitializeComponent()



this.listBox1 = new System.Windows.Forms.ListBox();

this.button1 = new System.Windows.Forms.Button();

this.button2 = new System.Windows.Forms.Button();

this.button3 = new System.Windows.Forms.Button();

this.button4 = new System.Windows.Forms.Button();

this.button5 = new System.Windows.Forms.Button();

this.button6 = new System.Windows.Forms.Button();

this.button7 = new System.Windows.Forms.Button();

this.SuspendLayout();

//

// listBox1

//

this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)

| System.Windows.Forms.AnchorStyles.Left)

| System.Windows.Forms.AnchorStyles.Right)));

this.listBox1.ItemHeight = 12;

this.listBox1.Location = new System.Drawing.Point(8, 8);

this.listBox1.Name = "listBox1";

this.listBox1.Size = new System.Drawing.Size(716, 460);

this.listBox1.TabIndex = 0;

//

// button1

//

this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button1.Location = new System.Drawing.Point(8, 488);

this.button1.Name = "button1";

this.button1.TabIndex = 1;

this.button1.Text = "Example1";

this.button1.Click += new System.EventHandler(this.button1_Click);

//

// button2

//

this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button2.Location = new System.Drawing.Point(96, 488);

this.button2.Name = "button2";

this.button2.TabIndex = 2;

this.button2.Text = "Example2";

this.button2.Click += new System.EventHandler(this.button2_Click);

//

// button3

//

this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));

this.button3.Location = new System.Drawing.Point(648, 488);

this.button3.Name = "button3";

this.button3.TabIndex = 3;

this.button3.Text = "Example7";

this.button3.Click += new System.EventHandler(this.button3_Click);

//

// button4

//

this.button4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button4.Location = new System.Drawing.Point(184, 488);

this.button4.Name = "button4";

this.button4.TabIndex = 4;

this.button4.Text = "Example3";

this.button4.Click += new System.EventHandler(this.button4_Click);

//

// button5

//

this.button5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button5.Location = new System.Drawing.Point(272, 488);

this.button5.Name = "button5";

this.button5.TabIndex = 5;

this.button5.Text = "Example4";

this.button5.Click += new System.EventHandler(this.button5_Click);

//

// button6

//

this.button6.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button6.Location = new System.Drawing.Point(360, 488);

this.button6.Name = "button6";

this.button6.TabIndex = 6;

this.button6.Text = "Example5";

this.button6.Click += new System.EventHandler(this.button6_Click);

//

// button7

//

this.button7.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

this.button7.Location = new System.Drawing.Point(448, 488);

this.button7.Name = "button7";

this.button7.TabIndex = 7;

this.button7.Text = "Example6";

this.button7.Click += new System.EventHandler(this.button7_Click);

//

// Form1

//

this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);

this.ClientSize = new System.Drawing.Size(728, 517);

this.Controls.Add(this.button7);

this.Controls.Add(this.button6);

this.Controls.Add(this.button5);

this.Controls.Add(this.button4);

this.Controls.Add(this.button3);

this.Controls.Add(this.button2);

this.Controls.Add(this.button1);

this.Controls.Add(this.listBox1);

this.Name = "Form1";

this.Text = "XMLReader";

this.ResumeLayout(false);

//

// xmlPath

//

this.xmlPath = "sample.xml";



#endregion

/// <summary>

/// 应用程序的主入口点。

/// </summary>

[STAThread]

static void Main()



Application.Run(new Form1());



private void button1_Click(object sender, System.EventArgs e)



xRead = new XmlReader(this.xmlPath,this.listBox1);

try



xRead.EachXml();



catch(XmlException xmlExp)



MessageBox.Show(xmlExp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



catch(Exception exp)



MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



finally



xRead.Dispose();





private void button2_Click(object sender, System.EventArgs e)



xRead = new XmlReader(this.xmlPath,this.listBox1);

try



xRead.ReadXmlByNodeType();



catch(XmlException xmlExp)



MessageBox.Show(xmlExp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



catch(Exception exp)



MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



finally



xRead.Dispose();





private void button3_Click(object sender, System.EventArgs e)



XmlNodeType[] xmlNType = XmlNodeType.Element, XmlNodeType.EndElement, XmlNodeType.XmlDeclaration;

xRead = new XmlReader(this.xmlPath, this.listBox1);

try



xRead.FilterByNodeType(xmlNType);



catch(XmlException xmlExp)



MessageBox.Show(xmlExp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



catch(Exception exp)



MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



finally



xRead.Dispose();





private void button4_Click(object sender, System.EventArgs e)



xRead = new XmlReader(this.xmlPath, this.listBox1);

try



xRead.ReadXmlTextValue();



catch(XmlException xmlExp)



MessageBox.Show(xmlExp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



catch(Exception exp)



MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



finally



xRead.Dispose();





private void button5_Click(object sender, System.EventArgs e)



xRead = new XmlReader(this.xmlPath, this.listBox1);

try



xRead.ReadXmlAttributes();



catch(XmlException xmlExp)



MessageBox.Show(xmlExp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



catch(Exception exp)



MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



finally



xRead.Dispose();





private void button6_Click(object sender, System.EventArgs e)



xRead = new XmlReader(this.xmlPath, this.listBox1);

try



xRead.ReadXmlNamespace();



catch(XmlException xmlExp)



MessageBox.Show(xmlExp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



catch(Exception exp)



MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



finally



xRead.Dispose();





private void button7_Click(object sender, System.EventArgs e)



xRead = new XmlReader(this.xmlPath, this.listBox1);

try



xRead.ReadXml();



catch(XmlException xmlExp)



MessageBox.Show(xmlExp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



catch(Exception exp)



MessageBox.Show(exp.ToString(),"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);



finally



xRead.Dispose();







参考技术B //
//bool XmlTextReader.Read(): 读取流中下一个节点,当读完最后一个节点再次调用该方法该方法返回false
//XmlNodeType XmlTextReader.NodeType: 该属性返回当前节点的类型
// XmlNodeType.Element 元素节点
// XmlNodeType.EndElement 结尾元素节点
// XmlNodeType.XmlDeclaration 文档的第一个节点
// XmlNodeType.Text 文本节点
//bool XmlTextReader.HasAttributes: 当前节点有没有属性,返回true或false
//string XmlTextReader.Name: 返回当前节点的名称
//string XmlTextReader.Value: 返回当前节点的值
//string XmlTextReader.LocalName: 返回当前节点的本地名称
//string XmlTextReader.NamespaceURI: 返回当前节点的命名空间URI
//string XmlTextReader.Prefix: 返回当前节点的前缀
//bool XmlTextReader.MoveToNextAttribute(): 移动到当前节点的下一个属性
//---------------------------------------------------------------------------------------------------

namespace XMLReading

using System;
using System.Xml;
using System.Windows.Forms;
using System.ComponentModel;

/// <summary>
/// Xml文件读取器
/// </summary>

public class XmlReader : IDisposable

private string _xmlPath;
private const string _errMsg = "Error Occurred While Reading ";
private ListBox _listBox;
private XmlTextReader xmlTxtRd;

#region XmlReader 的构造器

public XmlReader()

this._xmlPath = string.Empty;
this._listBox = null;
this.xmlTxtRd = null;


/// <summary>
/// 构造器
/// </summary>
/// <param name="_xmlPath">xml文件绝对路径</param>
/// <param name="_listBox">列表框用于显示xml</param>

public XmlReader(string _xmlPath, ListBox _listBox)

this._xmlPath = _xmlPath;
this._listBox = _listBox;
this.xmlTxtRd = null;


#endregion
#region XmlReader 的资源释放方法

/// <summary>
/// 清理该对象所有正在使用的资源

/// </summary>

public void Dispose()

this.Dispose(true);
GC.SuppressFinalize(this);


/// <summary>
/// 释放该对象的实例变量
/// </summary>
/// <param name="disposing"></param>

protected virtual void Dispose(bool disposing)

if (!disposing)
return;
if (this.xmlTxtRd != null)

this.xmlTxtRd.Close();
this.xmlTxtRd = null;


if (this._xmlPath != null)

this._xmlPath = null;



#endregion
#region XmlReader 的属性

/// <summary>
/// 获取或设置列表框用于显示xml
/// </summary>

public ListBox listBox

get

return this._listBox;

set

this._listBox = value;



/// <summary>
/// 获取或设置xml文件的绝对路径
/// </summary>

public string xmlPath

get

return this._xmlPath;

set

this._xmlPath = value;



#endregion

/// <summary>
/// 遍历Xml文件
/// </summary>

public void EachXml()

this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);

try

while(xmlTxtRd.Read())

this._listBox.Items.Add(this.xmlTxtRd.Value);


catch(XmlException exp)

throw new XmlException(_errMsg + this._xmlPath + exp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();



/// <summary>
/// 读取Xml文件的节点类型
/// </summary>

public void ReadXmlByNodeType()

this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);

try

while(xmlTxtRd.Read())

this._listBox.Items.Add(this.xmlTxtRd.NodeType.ToString());


catch(XmlException exp)

throw new XmlException(_errMsg + this._xmlPath + exp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();



/// <summary>
/// 根据节点类型过滤Xml文档
/// </summary>
/// <param name="xmlNType">XmlNodeType 节点类型的数组</param>

public void FilterByNodeType(XmlNodeType[] xmlNType)

this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);
try

while(xmlTxtRd.Read())

for (int i = 0; i < xmlNType.Length; i++)

if (xmlTxtRd.NodeType == xmlNType[i])

this._listBox.Items.Add(xmlTxtRd.Name + " is Type " + xmlTxtRd.NodeType.ToString());




catch(XmlException exp)

throw new XmlException(_errMsg + this.xmlPath + exp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();



/// <summary>
/// 读取Xml文件的所有文本节点值

/// </summary>

public void ReadXmlTextValue()

this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);

try

while(xmlTxtRd.Read())

if (xmlTxtRd.NodeType == XmlNodeType.Text)

this._listBox.Items.Add(xmlTxtRd.Value);



catch(XmlException xmlExp)

throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();



/// <summary>
/// 读取Xml文件的属性
/// </summary>

public void ReadXmlAttributes()

this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);

try

while(xmlTxtRd.Read())

if (xmlTxtRd.NodeType == XmlNodeType.Element)

if (xmlTxtRd.HasAttributes)

this._listBox.Items.Add("The Element " + xmlTxtRd.Name + " has " + xmlTxtRd.AttributeCount + " Attributes");

this._listBox.Items.Add("The Attributes are:");

while(xmlTxtRd.MoveToNextAttribute())

this._listBox.Items.Add(xmlTxtRd.Name + " = " + xmlTxtRd.Value);


else

this._listBox.Items.Add("The Element " + xmlTxtRd.Name + " has no Attribute");

this._listBox.Items.Add("");



catch(XmlException xmlExp)

throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();



/// <summary>
/// 读取Xml文件的命名空间
/// </summary>

public void ReadXmlNamespace()

this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);
try

while(xmlTxtRd.Read())

if (xmlTxtRd.NodeType == XmlNodeType.Element && xmlTxtRd.Prefix != "")

this._listBox.Items.Add("The Prefix " + xmlTxtRd.Prefix + " is associated with namespace " + xmlTxtRd.NamespaceURI);

this._listBox.Items.Add("The Element with the local name " + xmlTxtRd.LocalName + " is associated with" + " the namespace " + xmlTxtRd.NamespaceURI);


if (xmlTxtRd.NodeType == XmlNodeType.Element && xmlTxtRd.HasAttributes)

while(xmlTxtRd.MoveToNextAttribute())

if (xmlTxtRd.Prefix != "")

this._listBox.Items.Add("The Prefix " + xmlTxtRd.Prefix + " is associated with namespace " + xmlTxtRd.NamespaceURI);

this._listBox.Items.Add("The Attribute with the local name " + xmlTxtRd.LocalName + " is associated with the namespace " + xmlTxtRd.NamespaceURI);






catch(XmlException xmlExp)

throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();



/// <summary>
/// 读取整个Xml文件
/// </summary>

public void ReadXml()

string attAndEle = string.Empty;
this._listBox.Items.Clear();
this.xmlTxtRd = new XmlTextReader(this._xmlPath);

try

while(xmlTxtRd.Read())

if (xmlTxtRd.NodeType == XmlNodeType.XmlDeclaration)
this._listBox.Items.Add(string.Format("<?0 1 ?>",xmlTxtRd.Name,xmlTxtRd.Value));
else if (xmlTxtRd.NodeType == XmlNodeType.Element)

attAndEle = string.Format("<0 ",xmlTxtRd.Name);
if (xmlTxtRd.HasAttributes)

while(xmlTxtRd.MoveToNextAttribute())

attAndEle = attAndEle + string.Format("0='1' ",xmlTxtRd.Name,xmlTxtRd.Value);



attAndEle = attAndEle.Trim() + ">";
this._listBox.Items.Add(attAndEle);

else if (xmlTxtRd.NodeType == XmlNodeType.EndElement)
this._listBox.Items.Add(string.Format("</0>",xmlTxtRd.Name));
else if (xmlTxtRd.NodeType == XmlNodeType.Text)
this._listBox.Items.Add(xmlTxtRd.Value);


catch(XmlException xmlExp)

throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());

finally

if (this.xmlTxtRd != null)
this.xmlTxtRd.Close();





窗体代码如下:

namespace XMLReading



using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.Xml;

public class Form1 : System.Windows.Forms.Form



private System.Windows.Forms.ListBox listBox1;

private System.Windows.Forms.Button button1;

private System.Windows.Forms.Button button2;

private System.Windows.Forms.Button button3;

private System.Windows.Forms.Button button4;

private System.Windows.Forms.Button button5;

private System.Windows.Forms.Button button6;

private System.Windows.Forms.Button button7;

private string xmlPath;

private XmlReader xRead;

/// <summary>

/// 必需的设计器变量。

/// </summary>

private System.ComponentModel.Container components = null;

public Form1()



InitializeComponent();



/// <summary>

/// 清理所有正在使用的资源。

/// </summary>

protected override void Dispose( bool disposing )



if( disposing )



if (components != null)



components.Dispose();





base.Dispose( disposing );



#region Windows 窗体设计器生成的代码

/// <summary>

/// 设计器支持所需的方法 - 不要使用代码编辑器修改

/// 此方法的内容。

/// </summary>

private void InitializeComponent()



this.listBox1 = new System.Windows.Forms.ListBox();

this.button1 = new System.Windows.Forms.Button();

this.button2 = new System.Windows.Forms.Button();

this.button3 = new System.Windows.Forms.Button();

this.button4 = new System.Windows.Forms.Button();

this.button5 = new System.Windows.Forms.Button();

this.button6 = new System.Windows.Forms.Button();

this.button7 = new System.Windows.Forms.Button();

this.SuspendLayout();

//

// listBox1

//

this.listBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)

| System.Windows.Forms.AnchorStyles.Left)

| System.Windows.Forms.AnchorStyles.Right)));

this.listBox1.ItemHeight = 12;

this.list
参考技术C 和vb一样都是控件!
先安个vb,然后你进c#,添加控件。添加com那种。里面就有mscomm了。用他一切ok。
你要是用2005版的就不必麻烦了。2005在.net框架2.0下已经有自己的了,不用在用com了。幸福。。。
不过我还没转过去呢。在等破解的。
参考技术D Baidu,Google搜一下看看。

以上是关于C#基于控制台程序,一直获取串口数据的代码!谢谢!的主要内容,如果未能解决你的问题,请参考以下文章

自己编了个C#的串口调试程序,但发送命令后,得不到数据!找不到问题所在,想请教各位!谢谢,急用!

如何用C#构建三维空间

C#串口读取?

C#中怎么向串口发送数据

(高分求助)怎么用C#语言实现串口通讯,需要程序,急!

使用C#实现串口通讯,接受和控制单片机。