0

i m trying to write a method that does an estimate of the encoding of a file, i searched the msdn site and found this :

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();
}

My problem with the code above is that for large files, it reads the entire file before there's any sort of output, is there a way to limit this to reading just say, the first ten lines of a file?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
onlyf
  • 767
  • 3
  • 19
  • 39
  • 2
    This code gets the encoding from the BOM at the beginning of the file. It only reads it to the end to write its output. That part is not needed to get the encoding. – Sefe Nov 30 '17 at 10:22
  • Maybe I misunderstood the problem, but isn't that obvious that `while` loop is `Read()`'ing file and you need to remove it if you don't use it? – Renatas M. Nov 30 '17 at 10:29
  • 2
    @Reniuz, OP seems to be a beginner who copied code from [msdn](https://msdn.microsoft.com/en-us/library/system.io.streamreader.currentencoding(v=vs.110).aspx) without understanding what its doing... sigh... – Sinatr Nov 30 '17 at 10:30
  • @Sinatr true, true... – Renatas M. Nov 30 '17 at 10:36
  • 1
    Possible duplicate of [Read only the first few lines of text from a file](https://stackoverflow.com/questions/9439733/read-only-the-first-few-lines-of-text-from-a-file) – Sinatr Nov 30 '17 at 11:22
  • Possible duplicate of [How to detect the character encoding of a text file?](https://stackoverflow.com/questions/4520184/how-to-detect-the-character-encoding-of-a-text-file) – Jon Schneider Nov 30 '17 at 16:43

1 Answers1

1

You could use the System.Linq derivative and use the following;

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

That will read the first 10 lines of the file and store it in an array. you can then do a for loop to write the data in the array like this which should add a new line after each data is written.

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