c#查找文件编码

c# Find file encoding

我正在尝试编写一种方法来估计文件的编码,我搜索了 msdn 站点并找到了这个:

using (StreamReader sr = new StreamReader(openFileDialog1.FileName, true))
{

    using (var reader = new StreamReader(openFileDialog1.FileName, defaultEncodingIfNoBom, true))
    {
        reader.Peek(); // you need this!
        var encoding = reader.CurrentEncoding;
    }


    while (sr.Peek() >= 0)
    {
        Console.Write((char)sr.Read());
    }

    Console.WriteLine("The encoding used was {0}.", sr.CurrentEncoding);
    Console.ReadLine();
    Console.WriteLine();
    textBox4.Text = sr.CurrentEncoding.ToString();
}

我上面的代码的问题是,对于大文件,它会在有任何类型的输出之前读取整个文件,有没有办法将其限制为只读取文件的前十行?

您可以使用 System.Linq 导数并使用以下内容;

string[] first10Lines = File.ReadLines(path).Take(10).ToList();

这将读取文件的前 10 行并将其存储在一个数组中。然后你可以做一个for循环来像这样在数组中写入数据,这应该在每个数据写入后添加一个新行。

foreach (string line in first10Lines)
        {
        File.AppendAllText(newPathName, line);
        File.AppendAllText(newPathName, string.Format("{0}{1}", " ", Environment.NewLine));
        }