Yesterday
my client reported one issue she was facing on production server while
generating excel file.
Exception
read as: “System.ArgumentException
'.', hexadecimal value 0x00, is an invalid character”
After
further investigation I was able to replicate and exception is thrown due to
one string with troublesome characters (i.e. control and non-UTF-8 characters).
Solution:
I have
created one function (RemoveInvalidCharacters) to remove all the control and non-UTF-8
characters, and successfully removed all the troublesome characters.
/// <summary>
/// Method to remove control
characters and other non-UTF-8 characters
/// </summary>
/// <param name="inputStr">The string to process</param>
/// <returns>String with no non-UTF-8 characters</returns>
public static string
RemoveInvalidCharacters(string inputStr)
{
if (inputStr == null) return null;
var formattedStr = new StringBuilder();
foreach (var ch
in inputStr)
{
// remove all control characters and non-UTF-8
characters as all.
// except tabs and new lines
if ((ch < 0x00FD && ch > 0x001F) || ch == '\t'
|| ch == '\n' || ch == '\r')
{
formattedStr.Append(ch);
}
}
return formattedStr.ToString();
}
|
Hope this
solution helps you J
Comments
Post a Comment