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?
@before both your paths.filenamecreation, and inspect it, in both cases. If the generated string is the same, then your issue is not with string interpolation at all. If it's not the same, either you wrote it wrong, or there's a bug in the C# compiler.