[英]C# save txt file on desktop
如何保存我在桌面上創建的txt文件?
這是代碼:
void CreaTxtBtnClick(object sender, EventArgs e){
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
filePath = filePath + @"\Error Log\";
TextWriter sw = new StreamWriter(@"Gara.txt");
int rowcount = dataGridView1.Rows.Count;
for(int i = 0; i < rowcount - 1; i++){
sw.WriteLine(
dataGridView1.Rows[i].Cells[0].Value.ToString() + '\t' +
dataGridView1.Rows[i].Cells[1].Value.ToString() + '\t' +
dataGridView1.Rows[i].Cells[2].Value.ToString() + '\t' +
dataGridView1.Rows[i].Cells[3].Value.ToString() + '\t' +
dataGridView1.Rows[i].Cells[4].Value.ToString() + '\t' +
dataGridView1.Rows[i].Cells[5].Value.ToString() + '\t' +
dataGridView1.Rows[i].Cells[6].Value.ToString() + '\t' +
dataGridView1.Rows[i].Cells[7].Value.ToString() + '\t'
);
}
sw.Close();
MessageBox.Show("File txt creato correttamente");
}
我按照這些指示思考
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
filePath = filePath + @"\Error Log\";
TextWriter sw = new StreamWriter(@"Gara.txt");
我可以將文件保存在桌面上,但是在錯誤的路徑中正確創建了txt。 我該如何解決?
您已構建了filePath
,但尚未在TextWriter
使用它。 相反,您只需要寫入Gara.txt
文件,該文件默認位於應用程序啟動的文件夾中。
將您的代碼更改為:
filePath = filePath +@"\Error Log\Gara.txt";
TextWriter sw= new StreamWriter(filePath);
您必須將所有路徑部分組合到最終的filePath
:
string filePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"Error Log",
"Gara.txt");
我建議使用Linq來保存更易讀且更易於維護的數據:
File
.WriteAllLines(filePath, dataGridView1
.Rows
.OfType<DataGridViewRow>()
.Select(row => string.Join("\t", row
.Cells
.OfType<DataGridViewCell>()
.Take(8) // if grid has more than 8 columns (and you want to take 8 first only)
.Select(cell => cell.Value)) + "\t")); // + "\t": if you want trailing '\t'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.