在 WinForms 程式中,點擊按鈕(ID 為 a)時,以文本文件方式打開程式同目錄下的 app.xml,允許使用者手動編輯後保存。
TextBox(名為 textBox1),設置 MultiLine = true、ScrollBars = Vertical,方便多行編輯。Click 事件中讀取 XML 內容到文本框:string path = Path.Combine(Application.StartupPath, "app.xml");
if (File.Exists(path)) {
textBox1.Text = File.ReadAllText(path, Encoding.UTF8);
} else {
MessageBox.Show("找不到 app.xml");
}
File.WriteAllText(path, textBox1.Text, Encoding.UTF8);
MessageBox.Show("保存成功");
Application.StartupPath 獲取程式目錄,避免硬編碼路徑。Encoding.UTF8 防止中文亂碼。XDocument.Parse 驗證格式,避免寫入無效 XML。private void btnOpen_Click(object sender, EventArgs e) {
string file = Path.Combine(Application.StartupPath, "app.xml");
if (File.Exists(file))
textBox1.Text = File.ReadAllText(file, Encoding.UTF8);
else
MessageBox.Show("文件不存在");
}
private void btnSave_Click(object sender, EventArgs e) {
string file = Path.Combine(Application.StartupPath, "app.xml");
File.WriteAllText(file, textBox1.Text, Encoding.UTF8);
MessageBox.Show("已保存");
}