c# -如何从GZip中读取文本文件
本文关键字:读取 取文本 文件 GZip | 更新日期: 2023-09-27 18:07:37
这是我的问题,我试图使minecraft经典服务器,我使用文本系统使允许列表为每个地图,问题是文本系统使每个地图的文件,我们得到了大约15k个地图,所以如果1k的玩家添加允许列表到他们的地图,这将是很难上传/移动服务器到另一个主机。我想在我的软件的主文件夹中制作一个zip文件,并将每个文本文件添加到其中,并使其与系统可读,我想知道如何从GZip中读取文件,以及如何压缩文件。
谢谢
这是我非常简单的工作代码。无临时文件
using (FileStream reader = File.OpenRead(filePath))
using (GZipStream zip = new GZipStream(reader, CompressionMode.Decompress, true))
using (StreamReader unzip = new StreamReader(zip))
while(!unzip.EndOfStream)
ReadLine(unzip.ReadLine());
如果您想避免创建临时文件,您可以使用:
using (Stream fileStream = File.OpenRead(filePath),
zippedStream = new GZipStream(fileStream, CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(zippedStream))
{
// work with reader
}
}
如何使用GZip压缩和解压缩的详细信息。解压后,您可以使用StreamReader()类读取文件()的内容。NET 4.0)。
using System;
using System.IO;
using System.IO.Compression;
namespace zip
{
public class Program
{
public static void Main()
{
string directoryPath = @"c:'users'public'reports";
DirectoryInfo directorySelected = new DirectoryInfo(directoryPath);
foreach (FileInfo fileToCompress in directorySelected.GetFiles())
{
Compress(fileToCompress);
}
foreach (FileInfo fileToDecompress in directorySelected.GetFiles("*.gz"))
{
Decompress(fileToDecompress);
}
}
public static void Compress(FileInfo fileToCompress)
{
using (FileStream originalFileStream = fileToCompress.OpenRead())
{
if ((File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
{
using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fileToCompress.Name, fileToCompress.Length.ToString(), compressedFileStream.Length.ToString());
}
}
}
}
}
public static void Decompress(FileInfo fileToDecompress)
{
using (FileStream originalFileStream = fileToDecompress.OpenRead())
{
string currentFileName = fileToDecompress.FullName;
string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
using (FileStream decompressedFileStream = File.Create(newFileName))
{
using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
Console.WriteLine("Decompressed: {0}", fileToDecompress.Name);
}
}
}
}
}
}
源