繁体   English   中英

C#在桌面上保存txt文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM