0

I want to save a string to a file (without for example making \n into an actual new line).

This is my code:

using (var fs = new FileStream(path, FileMode.Truncate)
{
    var sw = new StreamWriter(fs);
    List<string> keys = texts.Keys.ToList();
    List<string> vals = texts.Values.ToList();
    for (int i = 0; i < texts.Count; i++)
    {
        sw.WriteLine(keys[i] + ";" + vals[i]);
    }
    sw.Close();
}

As you can see, I am trying to convert a dictionary called texts into a file. In the values, I can have line1\n\tline2. I need to somehow make, so that the escape characters dont convert into their actual form.

I would appreciate any help...

EDIT: Tried doing sw.WriteLine(keys[i].Replace(@"\", "|") + ";" + vals[i].Replace(@"\", "|");. It won't save as |n or |t...

EDIT 2: You can convert the Literal back to its original form using this oversized algorithm (not all escape characters included)

private static string ToNormal(string value)
    {
        string output = "";
        bool escapeChar = false;
        for (int i = 0; i < value.Length; i++)
        {
            if (escapeChar)
            {
                switch (value[i].ToString())
                {
                    case "n":
                        output += "\n";
                        break;
                    case "t":
                        output += "\t";
                        break;
                    case "a":
                        output += "\a";
                        break;
                    case @"\":
                        output += "\\";
                        break;
                }
                escapeChar = false;
            }
            else if (value[i] == '\\')
            {
                escapeChar = true;
                continue;
            }
            else
            {
                output += value[i];
            }
        }
        return output;
    }
RadarDev
  • 1
  • 1
  • Is the goal to write csv-files? if so you probably do not really want to escape linebreaks, but rather to encapsulate all the text in a cell. Or just use json instead and let the library handle everything. – JonasH Nov 03 '22 at 13:12

1 Answers1

0

See this question

Should be able to do this in the for loop:

sw.WriteLine(keys[i] + ";" + Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(vals[i], false));

You have to install the Microsoft.CodeAnalysis.CSharp Nuget package

frankM_DN
  • 365
  • 7