我正在使用 FileUpload 服务器控件从 MS Word 上传以前保存的 HTML 文档(作为网页;过滤)。字符集是 windows-1252。该文档具有智能引号(卷曲)以及常规引号。它也有一些空格(显然),当深入观察时,它们是普通 TAB 或 SPACE 以外的字符。
在 StreamReader 中捕获文件内容时,这些特殊字符将转换为问号。我假设它是因为默认编码是 UTF-8 并且文件是 Unicode。
我继续使用 Unicode 编码创建了 StreamReader,然后用正确的字符替换了所有不需要的字符(我实际上在 stackoverflow 中找到的代码)。这似乎有效....只是我无法将字符串转换回 UTF-8 以在 asp:literal 中显示它。代码在那里,它应该可以工作....但是输出(ConvertToASCII)是不可读的。
请看下面:
protected void btnUpload_Click(object sender, EventArgs e)
{
StreamReader sreader;
if (uplSOWDoc.HasFile)
{
try
{
if (uplSOWDoc.PostedFile.ContentType == "text/html" || uplSOWDoc.PostedFile.ContentType == "text/plain")
{
sreader = new StreamReader(uplSOWDoc.FileContent, Encoding.Unicode);
string sowText = sreader.ReadToEnd();
sowLiteral.Text = ConvertToASCII(sowText);
lblUploadResults.Text = "File loaded successfully.";
}
else
lblUploadResults.Text = "Upload failed. Just text or html files are allowed.";
}
catch(Exception ex)
{
lblUploadResults.Text = ex.Message;
}
}
}
private string ConvertToASCII(string source)
{
if (source.IndexOf('\u2013') > -1) source = source.Replace('\u2013', '-');
if (source.IndexOf('\u2014') > -1) source = source.Replace('\u2014', '-');
if (source.IndexOf('\u2015') > -1) source = source.Replace('\u2015', '-');
if (source.IndexOf('\u2017') > -1) source = source.Replace('\u2017', '_');
if (source.IndexOf('\u2018') > -1) source = source.Replace('\u2018', '\'');
if (source.IndexOf('\u2019') > -1) source = source.Replace('\u2019', '\'');
if (source.IndexOf('\u201a') > -1) source = source.Replace('\u201a', ',');
if (source.IndexOf('\u201b') > -1) source = source.Replace('\u201b', '\'');
if (source.IndexOf('\u201c') > -1) source = source.Replace('\u201c', '\"');
if (source.IndexOf('\u201d') > -1) source = source.Replace('\u201d', '\"');
if (source.IndexOf('\u201e') > -1) source = source.Replace('\u201e', '\"');
if (source.IndexOf('\u2026') > -1) source = source.Replace("\u2026", "...");
if (source.IndexOf('\u2032') > -1) source = source.Replace('\u2032', '\'');
if (source.IndexOf('\u2033') > -1) source = source.Replace('\u2033', '\"');
byte[] sourceBytes = Encoding.Unicode.GetBytes(source);
byte[] targetBytes = Encoding.Convert(Encoding.Unicode, Encoding.ASCII, sourceBytes);
char[] asciiChars = new char[Encoding.ASCII.GetCharCount(targetBytes, 0, targetBytes.Length)];
Encoding.ASCII.GetChars(targetBytes, 0, targetBytes.Length, asciiChars, 0);
string result = new string(asciiChars);
return result;
}
此外,正如我之前所说,还有一些更“透明”的字符似乎对应于单词 doc 具有编号缩进的位置,我不知道如何捕获它们的 unicode 值来替换它们......所以如果你有任何提示,请告诉我。
非常感谢提前!!