Search code examples
c#stringwysiwyg

How to read/append string in C# with exact spacing/tabs/lines


I have sample data

string test = @"allprojects {
                    repositories {
                        test()
                    }
               }"

When I read the test, I should get the exact string with spaces/tabs/new lines instead of me writing Environment.NewLine etc wherever it requires new line. When I print, it should print the same format [WYSIWYG] type.

Presently it gives something like this in debugger allprojects {\r\n\t\t repositories { \r\n\t\t test() \r\n\t\t } \r\n\t\t }


Solution

  • What I do in string literals that need this is just not indent the content at all:

    namespace Foo {
    
        class Bar {
    
            const string test = @"
    allprojects {
        repositories {
            test()
        }
    }";
    
        }
    
    }
    

    And strip away the initial newline. Looks a bit ugly, but it does get the point across that the leading whitespace matters.

    You can also place the @" on the second chance, but automatic code formatting could move that and it doesn't look as close to the actual text. (Code formatting should not touch the contents of a string, but I can't guarantee that.)

    This should round-trip correctly if processing the string line-by-line, as would seem appropriate anyway:

    var reader = new StringReader(test);
    reader.ReadLine();
    
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
    Console.ReadLine();
    

    Or just read them from a file / resource.