在C#中,可以使用System.IO.Compression命名空間中的類來對XML文件進行壓縮。下面是一個簡單的示例代碼:
using System;
using System.IO;
using System.IO.Compression;
using System.Xml;
public class XmlCompression
{
public static void CompressXmlFile(string filePath)
{
string compressedFilePath = filePath + ".gz";
using (FileStream originalFileStream = File.OpenRead(filePath))
{
using (FileStream compressedFileStream = File.Create(compressedFilePath))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
}
}
}
Console.WriteLine("XML file compressed successfully.");
}
public static void DecompressXmlFile(string compressedFilePath)
{
string decompressedFilePath = compressedFilePath.Replace(".gz", "");
using (FileStream compressedFileStream = File.OpenRead(compressedFilePath))
{
using (FileStream decompressedFileStream = File.Create(decompressedFilePath))
{
using (GZipStream decompressionStream = new GZipStream(compressedFileStream, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
}
}
}
Console.WriteLine("XML file decompressed successfully.");
}
public static void Main()
{
string filePath = "example.xml";
CompressXmlFile(filePath);
string compressedFilePath = filePath + ".gz";
DecompressXmlFile(compressedFilePath);
}
}
在上面的示例代碼中,我們定義了CompressXmlFile
方法和DecompressXmlFile
方法來分別壓縮和解壓縮XML文件。我們使用GZipStream
類來實現對XML文件的壓縮和解壓縮操作。在Main
方法中,我們先壓縮XML文件,然后再解壓縮已壓縮的XML文件。
請注意,壓縮后的文件擴展名為“.gz”,解壓縮時需要將其替換為原始XML文件的擴展名。