如何用C#删除文本文件输出中的奇怪字符

本文关键字:字符 输出 文件 何用 删除 文本 | 更新日期: 2023-09-27 18:06:05

我在C#中使用此代码显示一个文本文件

    string text = System.IO.File.ReadAllText(Server.MapPath(path));
    LabelContent.Text = text.ToString();

一旦显示文本,我就会得到这个(见下文-�- )特征:

    For fine-grained control over your PC�s power settings, click the
    �Change plan settings� link next to the power plan you�ve... 

我的问题是如何使用C#来摆脱这种情况?

我将感谢任何帮助。非常感谢。

如何用C#删除文本文件输出中的奇怪字符

您可以将Regex.Replace()与以下模式一起使用:

"[^''w''s''p{P}''p{Sm}<>]+"

这将匹配任何不是字母、数字、标点符号、空白字符、数学运算符或标记字符("<>"(的字符。任何与模式不匹配的字符,请将其替换为String.Empty如果最后还有其他字符需要保留,则必须将其添加到模式中

示例:

using System;
using System.Text.RegularExpressions;
public class Program
{
    public static void Main()
    {
        string fileContent = "    For fine-grained control over your PC�s power settings, click the'n" +
            "<p>    �Change plan settings� link next to the power plan you�ve... </p>";
        fileContent = Regex.Replace(fileContent, "[^''w''s''p{P}''p{Sm}<>]+", String.Empty);
        Console.WriteLine(fileContent);
    }
}

结果:

    For fine-grained control over your PCs power settings, click the
<p>    Change plan settings link next to the power plan youve... </p>

Fiddle演示

您遇到的问题是正确编码html中的UTF字符(我假设您使用的是ASP.NET(。如果搜索其他编码不起作用,我会尽量确保您编码为UTF-8 <meta charset="utf-8" />

好吧,我终于找到了如何摆脱那些烦人的角色(���).我所要做的就是用编码UTF-8而不是ANSI保存我的文本文件,ANSI是记事本中的默认选择。我不得不说,单独添加并不能解决问题。我不得不回到记事本,再次保存我的文件,但这次使用了不同的编码器(UTF-8(。

然而,我感谢你们所有人,感谢你们花时间帮助我。这个网站因为你们所有人而变得如此伟大。谢谢!!!!