首页 > 解决方案 > 解压缩文件夹时如何让文件自动覆盖现有文件?

问题描述

因此,我在这方面找到了很多信息,而且有很多不同的方式,因为我还是新手,所以这似乎非常压倒性。所以我的问题是,我如何将此功能合并到我自己的代码中,以便在提取文件时自动覆盖文件而不是给我一个错误?如果不是这样,有人可以将我引向易于理解和教我的教学领域吗?

以下是我当前有关从内存中保存和提取文件夹的代码。

public static void Extract(string nameSpace, string outDirectory, string internalFilePath, string resourceName)
{

    Assembly assembly = Assembly.GetCallingAssembly();

    using (Stream s = assembly.GetManifestResourceStream(nameSpace + "." + (internalFilePath == "" ? "" : internalFilePath + ".") + resourceName))
    using (BinaryReader r = new BinaryReader(s))
    using (FileStream fs = new FileStream(outDirectory + "//" + resourceName, FileMode.OpenOrCreate))
    using (BinaryWriter w = new BinaryWriter(fs))
        w.Write(r.ReadBytes((int)s.Length));

}

这就是我的业务目前正在发生的地方。

private void button2_Click(object sender, EventArgs e)
        {

            Extract("nameSpace", @"outDirectory", "internalFilePath", "resourceName");

            string sourceZipFile = @"C:\test.zip";
            string targetFolder = @"C:\";
            ZipFile.ExtractToDirectory(sourceZipFile, targetFolder);


            Process process = new Process();
            ProcessStartInfo p= new ProcessStartInfo();
            p.FileName = @"C:\test.zip";

            if ((System.IO.File.Exists(p.FileName)))
            {
                System.IO.File.Delete(p.FileName);
            }


        }

标签: c#overwrite

解决方案


使用具有overwriteFiles参数的正确重载:

ZipFile.ExtractToDirectory(sourceZipFile, targetFolder, true);

如果您在 Framework <= 4.8 上运行,那么您没有此功能。您必须自己编写逻辑


推荐阅读