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);
posted @ 2023-10-30 15:04  少年。  阅读(64)  评论(0编辑  收藏  举报