编码麻烦

时间:2011-10-28 09:26:51

标签: c# encoding

我的编码问题很严重。我正在使用的代码应该可以工作,但事实并非如此!

以下是代码:

FileStream fs = new FileStream(saveFile, FileMode.Create, FileAccess.Write, FileShare.None);

System.IO.StreamWriter objWriter;
objWriter = new System.IO.StreamWriter(fs , Encoding.Unicode);
string textLine;
if (System.IO.File.Exists(readFile) == true)
{
    System.IO.StreamReader objReader;
    objReader = new System.IO.StreamReader(readFile, Encoding.Unicode);

    do 
    {
        textLine = objReader.ReadLine();
        if (textLine.IndexOf(searchString) != -1)
        {
            tempString = textLine;
            position1 = textLine.IndexOf(searchString);

            tempString = textLine.Substring(position1);
            if (tempString.IndexOf("(") != -1)
            {
                position2 = tempString.IndexOf("(");
                //MessageBox.Show(tempString.Length.ToString());
                tempString = tempString.Substring(0, position2);
            }
        }

        objWriter.WriteLine(textLine);
    } while (objReader.Peek() != -1);
}
objWriter.Close();
MessageBox.Show(tempString);
MessageBox.Show("Done!");

我必须阅读一个混合英文字符和一些西里尔字符的文件,但在阅读和处理文件后,当我尝试将文件保存到新位置时,所有的cyrilic符号都是“?”或其他一些未知的符号。我尝试了所有可能的编码,它不起作用!

2 个答案:

答案 0 :(得分:4)

从您发布的示例来看,该文件似乎没有BOM,但它包含西里尔字符。如果没有BOM,则StreamReader无法猜测正确的编码。因此,您可以假定Windows-1251编码,因为该文件包含西里尔字符(根据您在评论部分中显示的HEX转储)。

所以这是你可以尝试的:

using (var reader = new StreamReader("input.txt", Encoding.GetEncoding("Windows-1251")))
using (var writer = new StreamWriter("output.txt", false, Encoding.UTF8))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // reading the input file line by line ...
        // perform the parsing and write to the UTF-8 output encoded file
        writer.WriteLine(line);
    }
}

答案 1 :(得分:1)

如果您不确定输入文件的编码,请不要指定它,让StreamReader实现检查。

我怀疑您的源文件不是Unicode,而是使用本地Windows编码。

制作一个全新的文件,不要在阅读器中指定任何编码。

objReader = new System.IO.StreamReader(readFile); 
相关问题