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;
}