为什么用html代码替换带重音符号的代码无法正常工作?

问题描述:

我想用相应的HTML代码(例如á,ñ,¿,¡等)替换带重音的字符(例如á,ñ,¿,¡等)。

I want to replace accented chars (such as á, ñ, ¿, ¡, etc.) with the corresponding HTML codes (such as á, ñ, ¿, ¡, etc.).

例如,以下文本行:


我不可能在saca rehusarmeálas repetidas instancias que el Caballero Trelawney,Livesey y otros muchos医生señoresme

Imposible me ha sido rehusarme á las repetidas instancias que el Caballero Trelawney, el Doctor Livesey y otros muchos señores me

...应该成为:


我不可能sido rehusarme & aacute; 美洲印第安人que el Caballero Trelawney,Livesey y otros muchos医生 se& ntilde; ores

Imposible me ha sido rehusarme á las repetidas instancias que el Caballero Trelawney, el Doctor Livesey y otros muchos señores me

这应该很简单。我有以下代码可以尝试:

This should be simple. I've got this code to make the attempt:

private void buttonReplaceCharsWithCodes_Click(object sender, EventArgs e)
{
    String fallName = String.Empty;
    List<String> linesModified = new List<string>();
    StreamReader file = null;

    try // finally
    {
        try // catch
        {

            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                fallName = openFileDialog1.FileName;
            }
            file = new StreamReader(fallName);
            String line;
            while ((line = file.ReadLine()) != null)
            {
                linesModified.Add(line);
            }

            progressBar1.Maximum = linesModified.Count;
            progressBar1.Value = 0;
            labelProgFeedback.Text = "Replacing accented chars with HTML codes";

            for (int i = 0; i < linesModified.Count; i++)
            {
                linesModified[i] = linesModified[i].Replace("á", "&aacute;");
                linesModified[i] = linesModified[i].Replace("Á", "&Aacute;");
                linesModified[i] = linesModified[i].Replace("é", "&eacute;");
                linesModified[i] = linesModified[i].Replace("É", "&Eacute;");
                linesModified[i] = linesModified[i].Replace("í", "&iacute;");
                linesModified[i] = linesModified[i].Replace("Í", "&Iacute;");
                linesModified[i] = linesModified[i].Replace("ñ", "&ntilde;");
                linesModified[i] = linesModified[i].Replace("Ñ", "&Ntilde;");
                linesModified[i] = linesModified[i].Replace("ó", "&oacute;");
                linesModified[i] = linesModified[i].Replace("Ó", "&Oacute;");
                linesModified[i] = linesModified[i].Replace("ú", "&uacute;");
                linesModified[i] = linesModified[i].Replace("Ú", "&Uacute;");
                linesModified[i] = linesModified[i].Replace("ü", "&uuml;");
                linesModified[i] = linesModified[i].Replace("Ü", "&Uuml;");
                linesModified[i] = linesModified[i].Replace("¿", "&iquest;");
                linesModified[i] = linesModified[i].Replace("¡", "&iexcl;");
                progressBar1.PerformStep();
            }
            progressBar1.Value = 0;
        }
        catch (Exception ex)
        {
            MessageBox.Show(String.Format("Exception {0}", ex.Message));
        }
    }
    finally
    {
        String massagedFileName = String.Format("{0}_Massaged.txt", fallName);
        File.WriteAllLines(massagedFileName, linesModified);
        file.Close();
    }

}

不幸的是,它不起作用。它用 what the heck?!?代替重音字符。符号( )而不是所需的HTML代码。要使其正常工作,需要执行什么操作?

Unfortunately, it doesn't work. It replaces the accented chars with the "what the heck?!?" symbol (�) instead of the HTML code desired. What is required to get this to work?

在回答这些评论时,这就是我加载的文件的内容:

In answer to the comments, this is the contents of the file I load:


我无法在
hecho para que es cribiese la historia circunstanciada上得到卡西耶罗·卡瓦列罗·特劳拉尼医生的身份, y完整的德拉泰索罗岛。 Voy,pues,áponer manosála obracontándolotodo,
desde el alfa hasta el omega ,sin dejarme cosa alguna en el tintero,exceptionaldo ladeterminacióngeográfica德拉伊斯拉·德·布拉·伊斯多拉·伊斯斯托·坦索·索戈拉·德戈·伊斯多·坦索·波多黎各存在于世界的任何地方。 ,您将获得17个月的收入证明书-以及波罗的海海军上将号, 您可以通过
的入门证书来访问您的网站,也可以从cur elementa的curtida
到s cicatriz。

Imposible me ha sido rehusarme á las repetidas instancias que el Caballero Trelawney, el Doctor Livesey y otros muchos señores me han hecho para que escribiese la historia circunstanciada y completa de la Isla del Tesoro. Voy, pues, á poner manos á la obra contándolo todo, desde el alfa hasta el omega, sin dejarme cosa alguna en el tintero, exceptuando la determinación geográfica de la isla, y esto tan solamente porque tengo por seguro que en ella existe todavía un tesoro no descubierto. Tomo la pluma en el año de gracia de 17-- y retrocedo hasta la época en que mi padre tenía aún la posada del "Almirante Benbow," y hasta el día en que por primera vez llegó á alojarse en ella aquel viejo marino de tez bronceada y curtida por los elementos, con su grande y visible cicatriz.

...这是它随替换文件保存的文件:

...and this is the file it saves with the replacements:


我不可能通过sido rehusarme-las repetidas
的Caballero Trelawney律师,Livesey y otros和其他医生为我提供了
的历史遗嘱通知书,以及
Isla del Tesoro的完整历史记录。 Voy,pues, ponermanos,la obra cont.ndolo todo,
desde el alfa hasta el omega ,sin dejarme cosa alguna en el tintero,exceptuando la确定地理标志的地理范围,是西班牙的esgo tan solamente porque tengo por seguro que en ella的存在。 Tomo la pluma en elaâode gracia de
17-y retrocedo hasta laâpocaen que mi padreten aaânla posada
del Almirante Benbow ,您必须先在
的基础上加油,然后再从curtida
的los elementos上购买,然后才能在cicatriz看到。

Imposible me ha sido rehusarme � las repetidas instancias que el Caballero Trelawney, el Doctor Livesey y otros muchos se�ores me han hecho para que escribiese la historia circunstanciada y completa de la Isla del Tesoro. Voy, pues, � poner manos � la obra cont�ndolo todo, desde el alfa hasta el omega, sin dejarme cosa alguna en el tintero, exceptuando la determinaci�n geogr�fica de la isla, y esto tan solamente porque tengo por seguro que en ella existe todav�a un tesoro no descubierto. Tomo la pluma en el a�o de gracia de 17-- y retrocedo hasta la �poca en que mi padre ten�a a�n la posada del "Almirante Benbow," y hasta el d�a en que por primera vez lleg� � alojarse en ella aquel viejo marino de tez bronceada y curtida por los elementos, con su grande y visible cicatriz.

IOW,替换没有发生-我只是看到了神秘字样,

IOW, the replacements are not happening - I'm just seeing the "mystery" character instead of the HTML codes.

当我单步执行代码并检查 linesModified的各个行时,在运行时会看到相同的内容。 (我看到了)。我猜比看星星要好。

I see the same thing at runtime when I step through the code and examine the individual lines of "linesModified" (I see �s). Better than seeing stars, I guess.

这是一个过程:这是一个简单的工具,单击按钮即可打开(.txt)文件。处理后,它将新版本的文件保存到新文件中。

This is the process: it's a simple util where I click the button to open the (.txt) file. After processing, it saves the new version of the file to a new file.

由于可以显式保存为UTF8,因此以为在读取文件时这样做也许会证明是有利的,但这:

Since it's possible to save explicitly as UTF8, I thought maybe doing so in reading the file may prove advantageous, but this:

while ((line = file.ReadLine(ASCIIEncoding.UTF8)) != null)

...不会编译,表示没有使用1个参数的ReadLine方法重载。

...doesn't compile, saying there is no overload of the ReadLine method that takes 1 argument.

我唯一能想到的就是专门在文件写入中指定编码,例如:

Only thing I can think of is specifically specifying your encoding on the file write, like:

File.WriteAllLines(massagedFileName, linesModified, Encoding.UTF8);