正在读取c#中的多语言文本文件

本文关键字:语言 文本 文件 读取 | 更新日期: 2023-09-27 18:01:04

我必须读取一个文本文件,其中可以包含来自以下语言的字符:英语、日语、中文、法语、西班牙语、德语、意大利语

我的任务是简单地读取数据并将其写入新的文本文件(将新行字符'n放在100个字符之后(。

我不能使用File.ReadAllTextFile.ReadAllLines,因为文件大小可能超过500 MB。所以我写了以下代码:

using (var streamReader = new StreamReader(inputFilePath, Encoding.ASCII))
{
      using (var streamWriter = new StreamWriter(outputFilePath,false))
      {
           char[] bytes = new char[100];
           while (streamReader.Read(bytes, 0, 100) > 0)
           {
                 var data = new string(bytes);
                 streamWriter.WriteLine(data);
           }
           MessageBox.Show("Compleated");
       }
}

除了ASCII编码,我还尝试过UTF-7UTF-8UTF-32IBM500。但在阅读和书写多种语言文字方面运气不佳。

请帮我实现这一点。

正在读取c#中的多语言文本文件

您必须查看正在解析的文件的前4个字节。这些字节将提示您必须使用什么编码。

以下是我为完成任务而编写的辅助方法:

public static string GetStringFromEncodedBytes(this byte[] bytes) {
    var encoding = Encoding.Default;
    var skipBytes = 0;
        if (bytes[0] == 0x2b && bytes[1] == 0x2f && bytes[2] == 0x76) {
            encoding = Encoding.UTF7;
            skipBytes = 3;
        }
        if (bytes[0] == 0xef && bytes[1] == 0xbb && bytes[2] == 0xbf) {
            encoding = Encoding.UTF8;
            skipBytes = 3;
        }
        if (bytes[0] == 0xff && bytes[1] == 0xfe) {
            encoding = Encoding.Unicode;
            skipBytes = 2;
        }
        if (bytes[0] == 0xfe && bytes[1] == 0xff) {
            encoding = Encoding.BigEndianUnicode;
            skipBytes = 2;
        }
        if (bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 0xfe && bytes[3] == 0xff) {
            encoding = Encoding.UTF32;
            skipBytes = 4;
        }

        return encoding.GetString(bytes.Skip(skipBytes).ToArray());
    }

这是一个很好的开始,可以找到答案。如果i不等于100,则需要读取更多的字符。像é这样的法语字符没有问题——它们都在C#字符类中处理。

char[] soFlow = new char[100];
int posn = 0;
using (StreamReader sr = new StreamReader("a.txt"))
   using (StreamWriter sw = new StreamWriter("b.txt", false))
      while(sr.EndOfStream == false)
      {
          try {
             int i = sr.Read(soFlow, posn%100, 100);
             //if i < 100 need to read again with second char array
             posn += 100;
             sw.WriteLine(new string(soFlow));
          }
          catch(Exception e){Console.WriteLine(e.Message);}
      } 

规范:读取(Char[],Int32,Int32(从指定索引开始,将当前流中指定的最多个字符读入缓冲区。

当然对我有用:(