0

I would like to read a line from a file, and use that line as the format specifier for a string.

The line in the file contains a newline character escape sequence \n. so it may look like this:

Hello{0}\n\nWelcome to the programme

And I want to use it in a situation like this:

string name_var = "Steve";    
string line = ReadLineFromFile();
string formatted_line = String.Format(line, name_var);

Unfortunately, the result looks like:

Hi Steve\n\nWelcome to the programme

Whereas I'd like it to look like:

Hi Steve

Welcome to the programme

Any ideas?

4
  • 2
    Would .Replace("\n", Environment.NewLine) work?
    – user247702
    May 28, 2014 at 13:45
  • 3
    Should be .Replace("\\n", Environment.NewLine)
    – amnezjak
    May 28, 2014 at 13:49
  • @Complexity that doesn't work.
    – Marcin
    May 28, 2014 at 13:53
  • thanks @Stijn and amnezjak - that was the right direction to go.
    – Marcin
    May 28, 2014 at 14:02

2 Answers 2

4

When you use escape sequences such as \n in your C# program, the compiler processes the string, and inserts the code of the corresponding non-printable character into the string literal for you.

When you read a line from a file or from another import source, processing of escape sequences becomes your program's responsibility. There is no built-in way of doing it. If all you want is \n, you could use a simplistic

formatString = formatString.Replace("\\n", "\n");

If you would like to support other escape sequences, such as ones for UNICODE characters, you could use solutions from answers to this question.

2

Replace the \n in your string with the newline specifier like this:

string name_var = "Steve"; 

string line = ReadLineFromFile();
line = line.Replace("\\n", Environment.NewLine);

string formatted_line = String.Format(line, name_var);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.