How To Use "{0}" In A File.WriteAllLines?

169 Views Asked by At

So, I am attempting to create multiple files with different names. I am trying to change one number in the file name like this, but it won't let me use "{0}" to insert a string.

String value = "1";

foreach (var message in reddit.User.PrivateMessages) {
  var pm = message as PrivateMessage;

  File.WriteAllText(
    (@"C:\Users\MyName\Desktop\Programming\test{0}.txt", value), 
    pm.Body);
}

The main point is I want to be able to create multiple files with a foreach loop. I can handle the int parsing seperately.

3

There are 3 best solutions below

0
Dmitry Bychenko On BEST ANSWER

You want formatting (String.Format):

File.WriteAllText(
   String.Format(@"C:\Users\MyName\Desktop\Programming\test{0}.txt", value),
   pm.Body);

In C#6.0 you may put it as string interpolation:

File.WriteAllText(
   $@"C:\Users\MyName\Desktop\Programming\test{value}.txt",
   pm.Body);
0
blogprogramisty.net On

You can't do this with File.WriteAllText.

Try this using string.format

 File.WriteAllText(string.format(@"C:\Users\MyName\Desktop\Programming\test{0}.txt", value), pm.Body);

or using c# 6.0 like this

File.WriteAllText($@"C:\Users\MyName\Desktop\Programming\test{value}.txt", pm.Body);
0
rory.ap On

You're code is broken currently; you left out string.Format(:

File.WriteAllText(string.Format(@"C:\Users\MyName\Desktop\Programming\test{0}.txt", value), pm.Body);