Reputation: 1
I would like to get the text from the textbox of my C# application into a .txt file. The issue I have is that the current saved file will overwrite the previously saved file. My current code is:
string log = @"C:\log.txt";
using (FileStream fs = new FileStream(log, FileMode.Create)) {
using (StreamWriter sw = new StreamWriter(fs)) {
foreach(string line in Textbox1.Lines)
sw.Write(line + sw.NewLine);
}
}
Is it possible to save the txt file but without it overwriting the previously saved file? Can someone help me with this.. Thanks
Upvotes: 0
Views: 7437
Reputation: 1662
Try
string log = @"C:\log"+ DateTime.Now.ToString("yyyyMMddHHmmssfffffff")+".txt";
this gives precision up to ten millionths of a second
Upvotes: 1
Reputation: 3045
try this ==>
string log = @"C:\log"+ new Guid().ToString("N") +".txt";
Upvotes: 0
Reputation: 19591
Try this
string log = @"C:\log"+ DateTime.Now.ToString("dd-MM-yyyy hh-mm-ss") +".txt";
Just add a time stamp to the file name
Upvotes: 3
Reputation: 632
If you want to write to the same file you could use FileMode.Append:
FileStream fs = new FileStream(log, FileMode.Append)
Take care if you're in a threaded environment (ie. asp.net which I suspect since you're talking about downloads), regarding file locks and such
Upvotes: 1
Reputation: 17850
I belive you are talking about appending the lines:
using(FileStream fs = new FileStream(log, FileMode.Append)) {
//...
}
Upvotes: 3
Reputation: 3398
This should help:
string log = @"C:\log.txt";
int intCounter = 0;
While(File.Exists(log))
{
log = @"C:\log"+ intCounter.ToString() +".txt";
}
Upvotes: 0