I have a function that should extract a .gz file and load it into memory, my question is, how do I read the content of the file once it has been loaded into memory without having to save it to disk first?
public static void Decompress2(FileInfo fileToDecompress)
{
using (FileStream fileStream = fileToDecompress.OpenRead())
{
using (var memStream = new MemoryStream())
{
string currentFileName = fileToDecompress.FullName;
string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream = new GZipStream(fileStream, CompressionMode.Decompress))
{
byte[] bytes = new byte[4096];
int n;
while ((n = decompressionStream.Read(bytes, 0, bytes.Length)) != 0)
{
memStream.Write(bytes, 0, n);
}
}
}
}
}
}
private int _bufferSize = 16384;
private void ReadFile(string filename)
{
StringBuilder stringBuilder = new StringBuilder();
FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
using (StreamReader streamReader = new StreamReader(fileStream))
{
char[] fileContents = new char[_bufferSize];
int charsRead = streamReader.Read(fileContents, 0, _bufferSize);
// Can't do much with 0 bytes
if (charsRead == 0)
throw new Exception("File is 0 bytes");
while (charsRead > 0)
{
stringBuilder.Append(fileContents);
charsRead = streamReader.Read(fileContents, 0, _bufferSize);
}
}
}
Hope it helps you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.