C# save txt file on desktop
11,078
Solution 1
You've constructed your filePath
, but haven't used it in TextWriter
. Instead you're just writing to Gara.txt
file which is by default located in the folder where your application started in.
Change your code to something like:
filePath = filePath +@"\Error Log\Gara.txt";
TextWriter sw= new StreamWriter(filePath);
Solution 2
You have to combine all path parts into the final filePath
:
string filePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"Error Log",
"Gara.txt");
I suggest using Linq to save the data which is more readable and easier to maintain:
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'
Author by
Matteo
Updated on June 04, 2022Comments
-
Matteo almost 2 years
How can I save a txt file that it was created by me on desktop?
This is the code:
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"); }
I thought that with these instructions
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); filePath = filePath + @"\Error Log\"; TextWriter sw = new StreamWriter(@"Gara.txt");
I can save the file on Desktop, but the txt is created correctly in the wrong path. How can I fix it?