建立xml對應的物件類
根節點,對應類名
[XmlRoot(“ComponentLog “)]
public class ComponentLog{
}
其他節點,對應屬性名
[XmlElement(“LogCategory”)]
public string logCategory { get; set; }
也可以對應集合(如果同一節點有多個的話)
[XmlElement(“LogContent”)]
public List<LogContent> logContent { get; set; }
節點裡的內容
[XmlAttribute(“Content”)]
public string content { get; set; }
XML檔案:
<?xml version=”1.0″ encoding=”utf-8″?>
<ComponentLog>
<LogCategory>Sign</LogCategory>
<LogContent>
<Key>1</Key>
<ContentCaption Content=”內容1″ VariableName=””/>
<ContentDetail Content=”內容2″ VariableName=”” />
</LogContent>
<LogContent>
<Key>2</Key>
<ContentCaption Content=”內容3″ VariableName=””/>
<ContentDetail Content=”內容4″ VariableName=”” />
</LogContent>
</ComponentLog>
窗體中開啟資料夾
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
txtFolderPath.Text = folderBrowser.SelectedPath;
}
窗體中跨執行緒呼叫元件(控制元件)
/// <param name=”textBox”>文字框</param>
/// <param name=”strText”>要顯示的內容</param>
private void ShowText(TextBox textBox, String strText)
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate () { ShowText(textBox, strText+”
“); });
}
else
{
textBox.Text += DateTime.Now + ” ” + strText+”
“;
}
}
關閉視窗,退出所有程式
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
System.Environment.Exit(0);
}
將文字框的滾動條一直處於最低端
private void txtReceive_TextChanged(object sender, EventArgs e)
{
txtReceive.SelectionStart = txtReceive.Text.Length;
txtReceive.ScrollToCaret();
}
連線字串
//str1不為空,就將str1和“ ”連線
string journalString = str1 != string.Empty ? string.Concat(str1, ” “) : string.Empty;
獲得程式執行目錄下指定檔案的路徑
string xmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, “JournalLog\123.xml”);
獲取指定的編碼格式
Encoding gb2312 = Encoding.GetEncoding(“GB2312”);
按照指定編碼格式讀取文字內容
string strRead = File.ReadAllText(xmlPath,Encoding.Default);
按照指定編碼格式轉換已經讀取到的文字內容
//sendByte是位元組,將其轉換成string
string strSendData = gb2312.GetString(sendByte);
或者string strSendData = Encoding.UTF8.GetString(sendByte);