Skip to content

Commit

Permalink
c# string escaping
Browse files Browse the repository at this point in the history
  • Loading branch information
robinrodricks committed Jul 15, 2019
1 parent ba43b11 commit 8594d52
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions FluentFTP/Utils/FtpExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -478,5 +478,43 @@ public static bool HasPermission(FtpPermission owner, FtpPermission flag) {
return (owner & flag) == flag;
}

/// <summary>
/// Escape a string into a valid C# string literal.
/// Implementation from StackOverflow - https://stackoverflow.com/a/14087738
/// </summary>
public static string EscapeStringLiteral(this string input) {
StringBuilder literal = new StringBuilder(input.Length + 2);
literal.Append("\"");
foreach (var c in input) {
switch (c) {
case '\'': literal.Append(@"\'"); break;
case '\"': literal.Append("\\\""); break;
case '\\': literal.Append(@"\\"); break;
case '\0': literal.Append(@"\0"); break;
case '\a': literal.Append(@"\a"); break;
case '\b': literal.Append(@"\b"); break;
case '\f': literal.Append(@"\f"); break;
case '\n': literal.Append(@"\n"); break;
case '\r': literal.Append(@"\r"); break;
case '\t': literal.Append(@"\t"); break;
case '\v': literal.Append(@"\v"); break;
default:

// ASCII printable character
if (c >= 0x20 && c <= 0x7e) {
literal.Append(c);
} else {

// As UTF16 escaped character
literal.Append(@"\u");
literal.Append(((int)c).ToString("x4"));
}
break;
}
}
literal.Append("\"");
return literal.ToString();
}

}
}

0 comments on commit 8594d52

Please sign in to comment.