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
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
I belive you are talking about appending the lines:
using(FileStream fs = new FileStream(log, FileMode.Append)) {
//...
}
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
Try
string log = @"C:\log"+ DateTime.Now.ToString("yyyyMMddHHmmssfffffff")+".txt";
this gives precision up to ten millionths of a second
This should help:
string log = @"C:\log.txt";
int intCounter = 0;
While(File.Exists(log))
{
log = @"C:\log"+ intCounter.ToString() +".txt";
}
试试这个==>
string log = @"C:\\log"+ new Guid().ToString("N") +".txt";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.