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

author author     2023-03-21     286

关键词:

调用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搜一下看看。

我需要利用modbus协议读取电能表的数据,请问该怎么读呢?语言是c#

...上下载了一个类库,虽然能读出数据了,但是还是不知道怎么获取返回的CRC码,我想得到返回的代码,包括地址、功能码、CRC码等。追答那你看一下modebus协议,已经给你定义好了,那一位是地址,那一位是功能码,那一位是crc嘛... 查看详情

高分求助:怎么处理百万条的excel数据

上百万的EXCEL数据,需要做一些筛选之类的简单处理。用什么程序可以达到的,EXCEL只能处理六万多条。看到有人说用Access,SQL什么的,但不是很懂,求高手指教!有时不止一百万,而且正如2L所说,直接用EXCEL处理这么庞大的信... 查看详情

c#做上位机,需要跟下位机施行串口通讯,原理是,下位机采集数据,通过串口传到pc机,我的环境是vs2008

...,功能不止如此。参考技术A这是串口通信方面的,我没怎么做过只是了解过,你在网上找一下serialport这个控件,不过有一点,这个控件在wpf里没有,所以你如果做的是wpf程序你可以通过io下面的serialport类来实现,需要引入usingSy... 查看详情

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

最好有现成的源程序,加注释。通常,在C#中实现串口通信,我们有四种方法:第一:通过MSCOMM控件这是最简单的,最方便的方法。可功能上很难做到控制自如,同时这个控件并不是系统本身所带,所以还得注册。可以访问http://... 查看详情

高分诚心求助!数据库设计如何实现不同用户进行不同操作的权限管理?!(数据库sql2000+编程语言c#)

具体问题:学生信息管理系统。有三类用户,学院教务处可以管理所有学生的数据,系教务处可以管理本系学生的数据。每个学生只可以管理自己的数据。数据库需要几个表,具体字段及实现不同用户进行不同操作的权限管理方... 查看详情

急急急!!!高分求助,c语言(c#,asp.net)写1至7随机4位数字组合,顺序不限,满意加分,

C++语言实现版本,和C语言是通用的,用的也是C的库,用C++的输入输出流更方便点,你用C的话把输入输出改改就行了!看了所有的问题,这应该是你想要的,贴上代码!#include<iostream>#include<stdlib.h>#include<time.h>using ... 查看详情

高分求助生成二维码的vb代码

我要做个二维码高速公路收费系统,求助达人们怎么编写生成二维码的vb代码~!!是vb语言哦。不好意思,我所有分数只有5分了,倾囊而出~!知道的好心人帮帮我哦。用PDF417动态库可生成2维条码阅读直接用2维条码扫描枪即可读... 查看详情

如何用c#构建三维空间

...来自串口的坐标数据控制小球在三维空间里移动。这个该怎么用C#实现呢?该查阅哪些资料呢?求大神指点。参考技术A不知道你想问什么,是怎么显示小球在三维空间里移动还是怎么用c#获取串口数据?这两个问题都很好解决,显... 查看详情

c#如何实现pc的串口通讯(一台pc双串口通讯),以下程序设计为啥不能发送接收,错在了哪里吗?

界面设置了两个Button按钮,按钮二用来发送数据,按钮一用来关闭程序;两个Textbox,Textbox2用来输入要发送的数据,Textbox1用来接收发送过来的数据。同时有两个serialPort控件和一个Timer控件。程序如下:namespaceWindowsFormsApplication11... 查看详情

c#串口通讯,复制粘贴就可用,仅仅介绍怎样最快的搭建一个串口通讯,异常拦截等等需要自己加上(代码片段)

原文:C#串口通讯,复制粘贴就可用,仅仅介绍怎样最快的搭建一个串口通讯,异常拦截等等需要自己加上usingSystem;usingSystem.Collections.Generic;usingSystem.IO.Ports;usingSystem.Text;//串口通讯类publicclassSerialPortManager//声明一个静态的串口资源... 查看详情

高分求助一道c语言设计题不难!!

1、题目:词汇统计器2、设计内容及要求:内容:统计任意的文本文件中指定的一组词汇出现的次数及位置。文本文件中存放的可以为英文文章。要求有程序最好还有比较详细的设计分析,我c语言很不好,所以最好有详细的分析... 查看详情

怎样获取串口地址

...新手我要编一个在vxworks从串口收发数据的程序但不知道怎么从串口读写请大侠们帮忙谢了vxworks中这样做也可以吗串口的地址我怎么知道如果是在操作系统中,你是不需要知道串口地址的。直接用设备名打开就可以。系统内的设... 查看详情

高分求助:用wpa_supplicant获取wifi热点信息时,如何区分wep加密方式是共享密钥的还是开放系统的?

本次提问不是一般的手工WiFi连接,是用程序调用这个工具,通过程序解析获取到的数据来判断网络连接里的每一个信号会有一个小锁子(应该在左下角),锁扣打开为开放式,锁扣闭合为加密模式。追问感谢回复,不过你的回... 查看详情

求助:用c#编写的winform窗体程序

用richtextbox控件实现如下功能,四大洋包括:【太平洋】、【大西洋】、【印度洋】、【北冰洋】。点击button按钮,【太平洋】等变成“________两个richtextbox框:一个放文本,一个放生成的题目。只能实现每一行的第一个【】。如... 查看详情

[高分求助]如何批量打印html文件~高分求助

...开打印,但是文件数量过大,寻求批量打印方法,谢谢,高分求助参考技术A1.c盘是否是NTFS格式,如果是,其格式将不被DOS识别,所以误格个别的盘。用NTFSforDOS就可以了。2.用EasyRecovery试一下。3.可以安装一键恢复精灵。4.等数据... 查看详情

c#编写pc与西门子1500通讯,用modbustcp协议

...B1.C#语言开发,采用NET4.0框架,模块化设计,通信效率不怎么高可以凑合用。2.工程结构类似OPC通讯方式,采用Tag的方式,通过标签名就可以读写寄存器。3.采用XML配置式标签的方式实时读写PLC内部寄存器,可读写寄存器包括I、Q... 查看详情

用c#语言开发上位机(来控制下位机比如了解下位机测量的温度湿度压力并控制下位机)要用到啥知识?

...和几个同学在做学校的项目。东西都是自己焊的,没有sdk怎么办?追答自己焊的?!你们好厉害啊。不管你怎么做的,总之想要能在电脑上跑起来,就必须有能驱动这个设备的方法。最底层应该是数模转换,上层一点的就是如何... 查看详情

c#自动更新程序怎么弄

用C#实现软件自动更新思路前言长期以来,广大程序员为到底是使用Client/Server,还是使用Browser/Server结构争论不休,在这些争论当中,C/S结构的程序可维护性差,布置困难,升级不方便,维护成本高就是一个相当重要的因素。有很... 查看详情