我有一个应该提取.gz文件并将其加载到内存中的函数,我的问题是,如何将文件内容加载到内存后如何读取文件的内容而不必先将其保存到磁盘? / p>
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);
}
}
}
}
}
}
答案 0 :(得分:0)
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);
}
}
}
希望它可以帮到你