引用IO命名空間:using System.IO;
在頁面拖一個saveFileDialog1控件;
private void btnJgbc_Click(object sender, EventArgs e)
{
try
{
DataTable myDT = new DataTable();
myDT = GvtoDT(ref myGV);
WriteTxt(myDT);
MessageBox.Show("保存成功!");
}
catch
{
MessageBox.Show("保存失敗!");
}
}
private void WriteTxt(DataTable tb)
{
StreamWriter sr;
string report;
if (File.Exists(Application.StartupPath + "\\MyFile3.txt")) //如果文件存在,則創建File.AppendText對象
{
sr = File.AppendText(Application.StartupPath + "\\MyFile3.txt");
report = "appended";
}
else //如果文件不存在,則創建File.CreateText對象
{
sr = File.CreateText(Application.StartupPath + "\\MyFile3.txt");
report = "created";
}
StringBuilder sb = new StringBuilder();
sr.WriteLine("注數\t紅1\t紅2\t紅3\t紅4\t紅5\t紅6\t藍1\t藍2\r\n");
foreach (DataRow dr in tb.Rows)
{
sr.WriteLine(dr[0].ToString() + "\t" + dr[1].ToString() + "\t" + dr[2].ToString() + "\t" + dr[3].ToString() + "\t" + dr[4].ToString() + "\t" + dr[5].ToString() + "\t" + dr[6].ToString() + "\t" + dr[7].ToString() + "\r\n");
}
sr.Close();
if( saveFileDialog1.ShowDialog()==DialogResult.OK)
{
File.Copy(Application.StartupPath + "\\MyFile3.txt", saveFileDialog1.FileName, true);
File.Delete(Application.StartupPath + "\\MyFile3.txt");
}
}