Can't access file which has been used by some other process

Refresh

December 2018

Views

1.1k time

1

Hi I am having a button in my WPF application which extracts set of files from a zip. I need to work with a file in the extracted folder. But after extraction if i access that file i keep getting an exception stating that "File has been used by other process, can't access" like that. I used Stream.flush(), Stream.Close(), Stream.Dispose(). None of them is usefull.

var zipFilePath = @"C:\Output.zip";
var tempFolderPath = @"C:\Unzipped";


    using (Package package = ZipPackage.Open(zipFilePath, FileMode.Open, FileAccess.Read))
    {
        foreach (PackagePart part in package.GetParts())
        {

            var target = Path.GetFullPath(Path.Combine(tempFolderPath, part.Uri.OriginalString.TrimStart('/')));
            var targetDir = target.Remove(target.LastIndexOf('\\'));

            if (!Directory.Exists(targetDir))
                Directory.CreateDirectory(targetDir);
            MemoryStream memoryStream = new MemoryStream(); 
           using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read))
           // using (Stream source = new FileStream(, FileMode.Open)) 
            {

              source.CopyTo(File.OpenWrite(target));
            //   CopyStreamTo(source, memoryStream); 
             }
        }

    }


    MessageBox.Show("Extracted in a folder");

          myclass obj=new myclass(@"C:\Unzipped\Something.xml");
        // Something.xml has been used by some other process  

Extraction works fine. But after extraction when i access file in C:\Unzipped\something.xml i keep getting this error."The process cannot access the file 'C:\Unzipped\Something.xml' because it is being used by another process." How can i solve it??

1 answers

3

You should dispose IDisposable resources by wrapping them in using statements:

using (Package package = ZipPackage.Open(zipFilePath, FileMode.Open, FileAccess.Read))
{
    foreach (PackagePart part in package.GetParts())
    {
        var target = Path.GetFullPath(Path.Combine(tempFolderPath, part.Uri.OriginalString.TrimStart('/')));
        var targetDir = target.Remove(target.LastIndexOf('\\'));

        if (!Directory.Exists(targetDir))
        {
            Directory.CreateDirectory(targetDir);
        }

        using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read))
        using (Stream targetFileStream = File.OpenWrite(target))
        {
            source.CopyTo(targetFileStream);
        }
    }
}