建立xml對應的對象類
根節點,對應類名
[XmlRoot("ComponentLog")]
publicclassComponentLog{
}
其餘節點,對應屬性名
[XmlElement("LogCategory")]
publicstringlogCategory{get;set;}
也能夠對應集合(若是同一節點有多個的話)
[XmlElement("LogContent")]
publicList<LogContent>logContent{get;set;}
節點裏的內容
[XmlAttribute("Content")]
publicstringcontent{get;set;}
XML文件:
<?xmlversion="1.0"encoding="utf-8"?>
<ComponentLog>
<LogCategory>Sign</LogCategory>
<LogContent>
<Key>1</Key>
<ContentCaptionContent="內容1"VariableName=""/>
<ContentDetailContent="內容2"VariableName=""/>
</LogContent>
<LogContent>
<Key>2</Key>
<ContentCaptionContent="內容3"VariableName=""/>
<ContentDetailContent="內容4"VariableName=""/>
</LogContent>
</ComponentLog>
窗體中打開文件夾
FolderBrowserDialogfolderBrowser=newFolderBrowserDialog();
if(folderBrowser.ShowDialog()==DialogResult.OK)
{
txtFolderPath.Text=folderBrowser.SelectedPath;
}
窗體中跨線程調用組件(控件)
///<paramname="textBox">文本框</param>
///<paramname="strText">要顯示的內容</param>
privatevoidShowText(TextBoxtextBox,StringstrText)
{
if(this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate(){ShowText(textBox,strText+"\r\n");});
}
else
{
textBox.Text+=DateTime.Now+""+strText+"\r\n";
}
}
關閉窗口,退出全部進程
privatevoidForm1_FormClosed(objectsender,FormClosedEventArgse)
{
System.Environment.Exit(0);
}
將文本框的滾動條一直處於最低端
privatevoidtxtReceive_TextChanged(objectsender,EventArgse)
{
txtReceive.SelectionStart=txtReceive.Text.Length;
txtReceive.ScrollToCaret();
}
鏈接字符串
//str1不爲空,就將str1和「」鏈接
stringjournalString=str1!=string.Empty?string.Concat(str1,""):string.Empty;
得到程序運行目錄下指定文件的路徑
stringxmlPath=Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"JournalLog\\123.xml");
獲取指定的編碼格式
Encodinggb2312=Encoding.GetEncoding("GB2312");
按照指定編碼格式讀取文本內容
stringstrRead=File.ReadAllText(xmlPath,Encoding.Default);
按照指定編碼格式轉換已經讀取到的文本內容
//sendByte是字節,將其轉換成string
stringstrSendData=gb2312.GetString(sendByte);
或者stringstrSendData=Encoding.UTF8.GetString(sendByte);ui