smoothgrips
smoothgrips

Reputation: 417

C# string interpolation throws IOException

I have a weird issue and am wondering if anyone else has come across this before. Perhaps I'm doing something wrong and someone can point out what I am doing wrong.

The issue is, I am creating a zip file and adding a bunch of files into it. I am wrapping the zip creation in a using, which should properly close the zip file after it finished adding files to it. The weird part is, when I use a regular string for the file's path, everything works fine. When I use string interpolation to create the path, instead of a regular string, it throws an IOException "the process cannot access the file because it is being used by another process".

Here's the code:

try
{
    string sourceDirectory = @"c:\path\to\files\that\need\zipping";
    string destinationDirectory = @"c:\path\to\zip\file";
    string zipFilename = "someFilename.zip";
    string filename = string.Format(@"{0}\{1}", destinationDirectory, zipFilename);
    //string filename = $@"{destinationDirectory}\{zipFilename}";
    using (ZipArchive zip = ZipFile.Open(filename, ZipArchiveMode.Create))
    {
        foreach (string pathToFile in Directory.GetFiles(sourceDirectory))
        {
            zip.CreateEntryFromFile(pathToFile, Path.GetFileName(pathToFile));
        }
    }
}
catch (IOException ex)
{
    // Lands here when using string interpolation.
}

The code above works and does not throw an IOException. However, when I comment out the string.Format() line uncomment the $@"{destinationDirectory}\{zipFilename}" line, it then throws the IOException.

Any thoughts as to why it would do that? Is the string interpolation somehow holding a handle on the file and not releasing it?

Upvotes: 0

Views: 737

Answers (2)

slash shogdhe
slash shogdhe

Reputation: 4187

Your code is perfect there is something else which is causing IOException. I tired running your code in both scenario you have mentioned ,its works good.

Upvotes: 0

Igor Ševo
Igor Ševo

Reputation: 5515

String interpolation cannot throw an IOException. The exception is probably thrown by the following line: using (ZipArchive zip = ZipFile.Open(filename, ZipArchiveMode.Create)).

You could test the program with and without string interpolation on differently named files to be sure.

Upvotes: 4

Related Questions