user1727958
user1727958

Reputation: 1

Save text from C# textbox to txt file. (Creating a new txt file everytime without same name of files)

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

Answers (6)

giftcv
giftcv

Reputation: 1662

Try

string log = @"C:\log"+ DateTime.Now.ToString("yyyyMMddHHmmssfffffff")+".txt";

this gives precision up to ten millionths of a second

Upvotes: 1

rt2800
rt2800

Reputation: 3045

try this ==>

string log = @"C:\log"+ new Guid().ToString("N") +".txt";

Upvotes: 0

yogi
yogi

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

Daniel
Daniel

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

DmitryG
DmitryG

Reputation: 17850

I belive you are talking about appending the lines:

using(FileStream fs = new FileStream(log, FileMode.Append)) {
    //...
}

Upvotes: 3

CodingBarfield
CodingBarfield

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

Related Questions