0
点赞
收藏
分享

微信扫一扫

c#实现文件压缩的方法

敬亭阁主 2023-10-30 阅读 33
// 实现一个压缩文件的方法
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 条评论