Reputation: 997
I have a particular issue. I have a data table which I want to have its data written to a text file. For this (I had already treat this in a previous tread) I used:
DataTable table = MyLibrary.dtRawData;
var fileLines = table
.AsEnumerable()
.Select(row => String.Join(" ", row.ItemArray))
.Where(line => !String.IsNullOrWhiteSpace(line));
try
{
File.WriteAllLines(filePath, fileLines);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
My problem is the WriteAllLines
function seems to always append data, if the file exists, but what I need is the file to be rewritten if already present at current location.What can I change from the code, in order to assure the file is overwritten and not appended?
Regards.
Upvotes: 2
Views: 574
Reputation: 51
The System.IO.File.WriteAllLines
method will overwrite an existing file with a new file if it has the same name in the same directory.
If you run the below lines of code consecutively
System.IO.File.WriteAllLines(@"C:\Users\{user}\Desktop\test.txt", new string[] { "e", "f", "g", "h" });
System.IO.File.WriteAllLines(@"C:\Users\{user}\Desktop\test.txt", new string[] { "a", "b", "c", "d" });
you will end up with one file containing the following content:
a
b
c
d
Upvotes: 2