c#实现文件压缩的方法

// 实现一个压缩文件的方法
public static void CompressFile(string sourceFilePath, string zipFilePath)
{
    // 如果文件没有找到,则报错
    if(!File.Exists(sourceFilePath))
    {
        throw new FileNotFoundException(sourceFilePath + "文件不存在!");
    }
    // 如果压缩文件没有找到,则进行创建
    if(!Directory.Exists(zipFilePath))
    {
        Directory.CreateDirectory(zipFilePath);
    }
    // 压缩文件的名称
    var zipFileName = zipFilePath + "\\" + Path.GetFileNameWithoutExtension(sourceFilePath) + ".zip";
    // 如果压缩文件存在,则进行删除
    if(File.Exists(zipFileName))
    {
        File.Delete(zipFileName);
    }
    // 开始压缩文件
    ZipFile.CreateFromDirectory(sourceFilePath, zipFileName);
}

方法示例

string sourceFilePath = "C:\\path\\to\\source\\file.txt";
string zipFilePath = "C:\\path\\to\\zip\\folder";

CompressFile(sourceFilePath, zipFilePath);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java实现文件压缩可以使用Java内置的ZipOutputStream类。下面是一个示例代码: ```java import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class FileCompressor { public static void main(String[] args) throws Exception { String sourceFile = "source.txt"; String compressedFile = "compressed.zip"; compress(sourceFile, compressedFile); } private static void compress(String sourceFile, String compressedFile) throws Exception { FileOutputStream fos = new FileOutputStream(compressedFile); ZipOutputStream zos = new ZipOutputStream(fos); File file = new File(sourceFile); FileInputStream fis = new FileInputStream(file); ZipEntry zipEntry = new ZipEntry(file.getName()); zos.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zos.write(bytes, 0, length); } zos.closeEntry(); fis.close(); zos.close(); fos.close(); } } ``` C#实现文件压缩可以使用System.IO.Compression.ZipArchive类。下面是一个示例代码: ```csharp using System.IO; using System.IO.Compression; class Program { static void Main(string[] args) { string sourceFile = "source.txt"; string compressedFile = "compressed.zip"; Compress(sourceFile, compressedFile); } private static void Compress(string sourceFile, string compressedFile) { using (FileStream fs = new FileStream(compressedFile, FileMode.Create)) { using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Create)) { zipArchive.CreateEntryFromFile(sourceFile, Path.GetFileName(sourceFile)); } } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值