0

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.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Cratherton
  • 17
  • 1
  • 9

3 Answers3

4

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);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

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);
blogprogramisty.net
  • 1,714
  • 1
  • 18
  • 22
0

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);
rory.ap
  • 34,009
  • 10
  • 83
  • 174