C# 在桌面上保存txt文件

标签 c# .net file 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);

关于C# 在桌面上保存txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40781396/

相关文章:

c# - 如何捕获这种类型的异常?

C#,从后台线程调用匿名方法(Action<>)

c# - 这些比较应该返回什么?

.net - 复制本地和系统 dll - 有什么意义?

c - 将结构传递给另一个 .c 文件中的函数,但它不指向正确的结构

git - 如何使用git只获取提交历史,而不是文件

python - 需要在 Python 中使用多个文件进行编程方面的帮助

c# - LinqKit PredicateBuilder 返回所有或非行

javascript - 如何使用jquery或javascript选择RadioButtonList中的列表项?

C# 如何为 selectedValue = null 设置 dropDownList 默认值