Is there a way to close a file in C#?
if(File.Exists(TEMP_FILENAME))
File.Delete(TEMP_FILENAME);
The above code complains that file is already used by another process.
Is there a way to check the open file handles in VS 2008?
Is there a way to close a file in C#?
if(File.Exists(TEMP_FILENAME))
File.Delete(TEMP_FILENAME);
The above code complains that file is already used by another process.
Is there a way to check the open file handles in VS 2008?
Close any streams using the file in your application.
If the error is due to another running applicaton, it's best to just try the operation, and deal with the failure. If you check, then try to perform the operation, you create a race condition. If the delete fails (whether due to file in use or permissions), just deal with the problem then.
I HAVE had this happen in VS2008 when running a program, stopping the execution once I've opened a file, and then running again and trying to do anything with the file. When that happens, the only way I've found to fix it is to close VS and re-open it, or kill the *.vshost.exe process, in order to release the file. I've never really looked into why it happens, but I assume it's because the actual process that runs as your app from VS is the *.vshost.exe file, which doesn't close when you end the execution of your program.
Also, to prevent this from happening, always either be sure to properly close your filestreams, or utilize a using
block. Make sure that this part of your code executes before ending execution via VS.
If this ISN'T what's happening, check the answer provided by mkus for how to see if another application has your file locked.
See if you can acquire a safehandle. This is something again unmanaged stuff. If you can acquire a safehandle it probably means the file is free for use.Refer the link:
http://msdn.microsoft.com/en-us/library/microsoft.win32.safehandles.safefilehandle.aspx