I have the following variable:
var setting =
$@"worker_processes {{0}};
worker_rlimit_nofile {{1}};
error_log logs/{{2}} {{3}};
events
{{
worker_connections {{4}};
multi_accept {{5}};
}}";
When I do the following String.Format()
operation on it:
return string.Format(setting,
this.worker_processes,
this.worker_rlimit_nofile,
this.error_log_file,
this.error_log_level,
this.worker_connections
this.multi_accept ? "on" : "off");
I get the following error: Input string was not in a correct format.
Any ideas?
EDIT - Fixed
Thanks to Jon Skeet, I have arrived at this solution without using String.Format()
:
return
$@"worker_processes { this.worker_processes };
worker_rlimit_nofile { this.worker_rlimit_nofile };
error_log logs/{ this.error_log_file } { this.error_log_level };
events
{{
worker_connections { this.worker_connections };
multi_accept { (this.multi_accept ? "on" : "off") };
}}";
It's unclear exactly what's going on as there's version confusion, but I suspect you just want:
var setting =
@"worker_processes {0};
worker_rlimit_nofile {1};
error_log logs/{2} {3};
events
{{
worker_connections {4};
multi_accept {5};
}}";
Now the braces for the events
block will still be escaped, but the rest will be treated as format specifiers.
Here's a full example:
using System;
class Test
{
static void Main(string[] args)
{
var setting =
@"worker_processes {0};
worker_rlimit_nofile {1};
error_log logs/{2} {3};
events
{{
worker_connections {4};
multi_accept {5};
}}";
string text = string.Format(setting, 10, true, "log.txt", "debug", 20, false);
Console.WriteLine(text);
}
}
Output:
worker_processes 10;
worker_rlimit_nofile True;
error_log logs/log.txt debug;
events
{
worker_connections 20;
multi_accept False;
}
Or using string interpolation from C# 6:
return $@"worker_processes {worker_processes};
worker_rlimit_nofile {worker_rlimit_nofile};
error_log logs/{error_log_file} {error_log_level};
events
{{
worker_connections {worker_connections};
multi_accept {multi_accept};
}}";
See more on this question at Stackoverflow