Search code examples
c#.netsftpdotnetzipssh.net

Getting "it is being used by another process" after trying to extract a ZIP file downloaded from SFTP server using SSH.NET


I got a problem when I want to unzip a file.

After I download a file from SFTP, I want to unzip that, but it always tells me it's being used by another process.

I want to find the question by google but it seems nobody has this question.

Can somebody teach me how to solve it? Thank you a lot.

bool result = false;
string zipFile = "";

using (SftpClient sftp = new SftpClient(ip, user, pw))
{
    sftp.Connect();
    var sftpFiles = GetFileList("/", sftp);
    zipFile = GetZipFile(sftpFiles);
    if (zipFile != null)
    {
        var file = File.OpenWrite(fileName);
        sftp.DownloadFile(fileName,file);
        result = true;
        sftp.Disconnect();
    }
}
if (result)
{
    using (ZipFile zipList = ZipFile.Read(fileName))
    {
        ZipEntry zipFile = zipList[fileName];
        zipFile.Extract("/", ExtractExistingFileAction.OverwriteSilently);
    }
}

Solution

  • You do not close the file after you download it.

    The download code should be like:

    using (var file = File.OpenWrite(fileName))
    {
        sftp.DownloadFile(fileName, file);
    }