Jishan
Jishan

Reputation: 1684

Writing Content of Textbox To .txt File

I want to write all the content of a textbox to a .txt file to the current directory. I wrote the following code however it throws a "wrong path name error". Where have I gone wrong?

string fileDateTime = "StepsGA-" + DateTime.Now + ".txt";
string fname = System.IO.Path.Combine(System.Environment.CurrentDirectory, fileDateTime);
File.WriteAllText(fname, txtSteps.Text); 

Thanks.

Upvotes: 0

Views: 322

Answers (3)

Syed Fahad Ali
Syed Fahad Ali

Reputation: 59

a file name cant contain /\^<>*!| you need to have formate date you may use following code to formate your date String.Format("{0:y yy yyy yyyy}", DateTime.Now); this will return date as 8 08 008 2008

so change your code as following string fileDateTime = "StepsGA-" + String.Format("{0:y yy yyy yyyy}", DateTime.Now) + ".txt"; string fname = System.IO.Path.Combine(System.Environment.CurrentDirectory, fileDateTime); File.WriteAllText(fname, txtSteps.Text);

hope this will work for you now

Upvotes: 0

Keith Nicholas
Keith Nicholas

Reputation: 44316

you probablly want to do DateTime.Now.ToString("yyyyMMddHHmmss")

This has the added advantage that if you sort by name, it will be in date order.

Upvotes: 2

Stepan Yakovenko
Stepan Yakovenko

Reputation: 9216

may be DateTime.now includes ':' char? You can't use this char in file name...

Upvotes: 1

Related Questions