Zara Gheorghe
Zara Gheorghe

Reputation: 488

How to create a custom file name with a formatted DateTime object?

I want to save my data to a text file but the file name must contain 2 diferent strings, here's what I've do so far:

string input = "Name_"
string input2 = string.Format("stats-{0:yyyy-MM-dd}.txt",
        DateTime.Now);

and I can't figure it out how to add here: string.Format(input, "stats... and the file name must be like:

*Name_stats-2013-11-27.txt*

Upvotes: 0

Views: 900

Answers (4)

JSQuareD
JSQuareD

Reputation: 4776

Strings can be concatenated simply by using the + operator:

string filename = input + input2;

Also, you can add multiple tags to your format-operation:

string format = string.Format("{0}stats-{1:yyyy-MM-dd}.txt", input, DateTime.Now);

Upvotes: 5

Nerd in Training
Nerd in Training

Reputation: 2220

Why not try this? Make your life easier...

string input2 = string.Format("{0} stats-{1:yyyy-MM-dd}.txt", input, DateTime.Now);

Upvotes: 1

rae1
rae1

Reputation: 6144

Just do,

string input = "Name_"
string input2 = string.Format("stats-{0:yyyy-MM-dd}.txt",
    DateTime.Now);
var fileName = input + input2;

or alternatively,

var fileName = string.Format(
    "{0}stats-{1:yyyy-MM-dd}.txt",
    "Name_", // Or an actual name
    DateTime.Now)

Upvotes: 3

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

With Format you start counting at 0 and then continue to count up each placeholder. So your text would be

string result = string.Format("{0}stats-{1:yyyy-MM-dd}.txt", input, DateTime.Now);

Upvotes: 2

Related Questions