使用unicode字符读取文件

chr*_*ris 12 c# asp.net unicode

我有一个asp.net c#页面,我正在尝试读取具有以下字符的文件并将其转换为'.(从倾斜的撇号到撇号).

FileInfo fileinfo = new FileInfo(FileLocation);
string content = File.ReadAllText(fileinfo.FullName);

//strip out bad characters
content = content.Replace("’", "'");
Run Code Online (Sandbox Code Playgroud)

这不起作用,它将倾斜的撇号变为?分数.

Jus*_*tin 15

我怀疑问题不在于替换,而在于读取文件本身.当我尝试这种方式(使用Word和复制粘贴)时,我得到了与您相同的结果,但是检查content显示.Net框架认为该字符是Unicode字符65533,即"WTF?" 字符之前的字符串替换.您可以通过检查Visual Studio调试器中的相关字符来自行检查,它应显示字符代码:

content[0]; // 65533 '?'
Run Code Online (Sandbox Code Playgroud)

替换不起作用的原因很简单 - content不包含您给它的字符串:

content.IndexOf("’"); // -1
Run Code Online (Sandbox Code Playgroud)

至于为什么文件读取不正常 - 您在读取文件时可能使用了错误的编码.(如果没有指定编码,则.Net框架将尝试为您确定正确的编码,但是没有100%可靠的方法来执行此操作,因此通常会出错).您需要的确切编码取决于文件本身,但在我的情况下,使用的编码是扩展ASCII,因此要读取我只需要指定正确编码的文件:

string content = File.ReadAllText(fileinfo.FullName, Encoding.GetEncoding("iso-8859-1"));
Run Code Online (Sandbox Code Playgroud)

(见这个问题).

您还需要确保在替换字符串中指定正确的字符 - 在代码中使用"奇数"字符时,您可能会发现通过字符代码指定字符更可靠,而不是字符串文字(这可能会导致如果源文件的编码发生变化,则会出现问题,例如以下内容对我有用:

content = content.Replace("\u0092", "'");
Run Code Online (Sandbox Code Playgroud)

  • 而不是`(char)146`,`'\ u0092'可能更具可读性,因为它与字符代码图表匹配. (2认同)

Tre*_*oll 2

// This should replace smart single quotes with a straight single quote

Regex.Replace(content, @"(\u2018|\u2019)", "'");

//However the better approach seems to be to read the page with the proper encoding and leave the quotes alone
var sreader= new StreamReader(fileInfo.Create(), Encoding.GetEncoding(1252));
Run Code Online (Sandbox Code Playgroud)