None of the code you posted actually does anything other than check for a file to exist. This code doesn't open any files so it wouldn't trigger the error you're talking about. What you need to do is look at the file that is being locked (I assume mainPath
) and ensure that any calls to open the file also close the file. That is what the using statement is for.
using (var stream = File.OpenWrite(mainPath))
{
}; //File is automatically closed when done, even on error
//File is never properly closed
var stream2 = File.OpenWrite(mainPath);
stream2.Close(); //Don't do this as it is not exception safe
//Will fail because file is already open, doesn't matter that it is the same process
var stream3 = File.OpenWrite(mainPath);
If you're using some data library or something that wraps all this then you need to ensure it is cleaning things up as well.