創建xml對應的對象類 根節點,對應類名 [XmlRoot("ComponentLog ")] public class ComponentLog{ } 其他節點,對應屬性名 [XmlElement("LogCategory")] public string logCategory { get; s ...
創建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+"\r\n"); });
}
else
{
textBox.Text += DateTime.Now + " " + strText+"\r\n";
}
}
關閉視窗,退出所有進程
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);