Morgan Green Morgan Green - 18 days ago 5
C# Question

Wait for previous function to complete

I'm working on a web installer and one of the things I have currently is

void MoveFiles()
{
lbldlstatus.Text = "Moving Files";
string InstallDirectory = Directory.GetCurrentDirectory() + "/DoxramosRepack-master";
DirectoryInfo d = new DirectoryInfo(InstallDirectory);
foreach(var file in d.GetFiles("*"))
{
try
{
if (File.Exists(file.Name)) {
File.Delete(file.Name);
}

Directory.Move(file.FullName, file.Name);
Cleanup();
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
lbldlstatus.Text = "Repack Installation Failed";
}
}
}
void Cleanup()
{
lbldlstatus.Text = "Cleaning Up Files";
try
{
if (File.Exists("Repack.zip"))
{
File.Delete("Repack.zip");
}
if(Directory.Exists("DoxramosRepack-master"))
{
Directory.Delete("DoxramosRepack-master");
}
lbldlstatus.Text = "Repack Installed Successfully";
}


When I get to
Cleanup()
I have a
System.IO.IOException
.


Process cannot access the file Repack.zip because it being used by
another process.


The full code runs

Download->Extract->Move->Cleanup.

I'm not sure what process is being used, but I'm looking to find a way for each process to wait for the previous to finish before starting.

Answer

According to extract code below

void Extract()
{
    string zipPath = @"Repack.zip";
    string extractPath = @".";
    try
    {
        using (ZipFile unzip = ZipFile.Read(zipPath))
        {
            unzip.ExtractAll(extractPath);
            lbldlstatus.Text = "Extracting Files";
            MoveFiles();               
        }
    }
    catch (ZipException e)
    {
        MessageBox.Show(e.ToString());
        lbldlstatus.Text = "Repack Installation Failed";
    }
}

You are calling the move files before you are finish with the zip file. Seeing as the move file method is responsible for calling the clean up function then you should make sure that the zip file is already disposed of before trying to delete it.

void Extract()
{
    string zipPath = @"Repack.zip";
    string extractPath = @".";
    try
    {
        using (ZipFile unzip = ZipFile.Read(zipPath))
        {
            unzip.ExtractAll(extractPath);
            lbldlstatus.Text = "Extracting Files";
        }
        MoveFiles();
    }
    catch (ZipException e)
    {
        MessageBox.Show(e.ToString());
        lbldlstatus.Text = "Repack Installation Failed";
    }
}

Clean up should also be called after everything has been moved. Currently the example code is calling it repeatedly in the for loop.

Comments