/// Beim Speichern von Strings in Textdateien möchte man manchmal, dass Literale (Zeilenumbrüche, Tabs usw.)
/// nicht interpretiert werden, sondern als hexadezimale Codierungen gespeichert werden.
/// die statische Klasse wandelt alle ASCII-Steuerzeichen in einem String mit ASCIICode < 32 in die entsprechenden hexadezimalen Pendants um.
using System;
/// <summary>
/// freeware helper class for converting string formats
/// (W) 2011 by admin of codezentrale.6x.to
/// </summary>
public static class StringConverter
{
/// <summary>
/// hex replace of literals
/// </summary>
/// <param name="path">a string</param>
/// <returns>string with replaced literals</returns>
public static string ReplaceLiterals(string inputstring)
{
string output = string.Empty;
foreach (char t in inputstring)
{
int ascii = Convert.ToInt32(t);
output += (ascii < 32) ? string.Format("&#x{0:X02};", ascii) : t.ToString();
}
return output;
}
}
Beispiel:
string sInput = "Hallo" + Environment.NewLine + "Welt!" // "Hallo Welt!" string sOutPut = StringConverter.ReplaceLiterals(sInput));