How can I have files automatically overwrite existing files when unzipping my folder?

Viewed 151

So there is a lot of information I have found on this and so many different ways it seems very overwhelming since I'm still new to this. So my question is, how would I incorporate this feature into my own code of it automatically overwriting files when its extracting instead of giving me an error? If not that, can someone throw me in the direction of an instructional area that is easy to understand and teach me?

Below is my current code on saving and extracting the folder from memory.

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));

}

And here is where my business is happening currently.

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);
            }


        }
1 Answers

Use the correct overload that has overwriteFiles parameter:

ZipFile.ExtractToDirectory(sourceZipFile, targetFolder, true);

If you are running on Framework <= 4.8, then you don't have this function. You will have to write the logic yourself

Related