这是我的问题,我正在尝试制作我的世界经典服务器,我正在使用文本系统为每个地图制作允许列表,问题是文本系统为每个地图制作一个文件,我们总共获得了大约15k个地图因此,如果1k的玩家将允许列表添加到他们的地图中,则很难将服务器上传/移动到另一个主机。我想在我的软件的主文件夹中创建一个zip文件,并将每个文本文件添加到它,并使系统可读,我想知道如何从GZip读取文件,以及如何压缩文件。
由于
答案 0 :(得分:12)
这是我非常简单的工作代码。没有临时文件
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());
答案 1 :(得分:7)
如果您想避免创建临时文件,可以使用:
using (Stream fileStream = File.OpenRead(filePath),
zippedStream = new GZipStream(fileStream, CompressionMode.Decompress))
{
using (StreamReader reader = new StreamReader(zippedStream))
{
// work with reader
}
}
答案 2 :(得分:4)
有关如何使用GZip进行压缩和解压缩的详细信息。解压缩后,您可以使用StreamReader() class来读取文件的内容(.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);
}
}
}
}
}
}