2016-11-24 325 views
4

如何保存由我在桌面上创建的txt文件?C#在桌面上保存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在错误的道路正确创建。 我该如何解决它?

+0

它保存在哪里? – active92

+1

在程序文件夹中 – Matteo

回答

6

您已构建您的filePath,但尚未在TextWriter中使用它。相反,你只是写Gara.txt文件,该文件默认情况下位于您的应用程序在启动文件夹中

更改您的代码是这样的:。

filePath = filePath [email protected]"\Error Log\Gara.txt"; 
TextWriter sw= new StreamWriter(filePath); 
+4

请注意,最好使用'Path.Combine()'而不是字符串连接来构建文件路径。 –

+1

还要注意,默认值是应用程序启动的目录,而不是可执行文件所在的目录。例如。如果您当前位于目录'C:\ tmp'中并且您在'C:\ Program Files \ SomeFolder \ MyApp.exe'中启动了您的应用程序,则当前目录将为'C:\ tmp'(除非您的应用程序或开始进程时的参数,例如通过使用'start'命令)。 –

+0

@DirkVollmar错过了,谢谢。 –

3

你必须结合所有路部分成最终filePath

string filePath = Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.Desktop), 
    "Error Log", 
    "Gara.txt"); 

我建议使用的LINQ保存哪个更可读和e中的数据asier维护:

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' 
+0

您错过了每行结尾处的最后一个'\ t''。 – Maarten

+0

@Maarten:我明白了,谢谢!然而,最后的*尾部列表*实际上是多余的(所以我添加了评论) –

+0

实际上,尾部的'\ t'看起来像一个错误(但是当然,我们没有知道文件格式的确切规格。可能是这样一个奇怪的实际需要)。尽管如此,这种解决方案通过使用字符串生成器(直接写入流而不构建行可能更高效)避免了大量字符串连接。 –