1

Is there a way to use the one-liner ReadAllLines on a gzipped file?

var pnDates = File.ReadAllLines("C:\myfile.gz");

Can I put GZipStream wrapper around the file some how?

ManInMoon
  • 6,795
  • 15
  • 70
  • 133

3 Answers3

4

No, File.ReadAllLines() treats the file specified as text file. A zipfile isn't that. It's trivial to do it yourself:

public IEnumerable<string> ReadAllZippedLines(string filename)
{
    using (var fileStream = File.OpenRead(filename))
    {
        using (var gzipStream = new GZipStream(fileStream, CompressionMode.Decompress))
        {
            using (var reader = new StreamReader(gzipStream)) 
            {
                yield return reader.ReadLine();
            }
        }
    }
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • I am not very familiar with yield. It appears to be doing an implicit while((line=reader.ReadLine())=!null) { return line;}. Have I got the right idea? – ManInMoon Nov 26 '14 at 11:44
  • See [yield (C# Reference)](http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx). It causes the method to read and return one line at a time, instead of reading the entire file in memory at once. – CodeCaster Nov 26 '14 at 11:45
0

There is no such thing built-in. You'll have to write yourself a small utility function.

usr
  • 168,620
  • 35
  • 240
  • 369
0

You'd have to inflate the file first as the algorithm for gzip deals with byte data not text and incorporates a CRC. This should work for you: EDIT - I cant comment for some reason, so this if for the bytestocompress question


byte[] decompressedBytes = new byte[4096];
using (FileStream fileToDecompress = File.Open("C:\myfile.gz", FileMode.Open))
{
    using (GZipStream decompressionStream = new GZipStream(fileToDecompress, CompressionMode.Decompress))
    {
        decompressionStream.Read(decompressedBytes, 0, bytesToCompress.Length);
    }
}
var pnDates = System.Text.Encoding.UTF8.GetString(decompressedBytes);
dovid
  • 6,354
  • 3
  • 33
  • 73
Kell
  • 3,252
  • 20
  • 19