Reputation: 11
In my application, I need to delete files and then remove the directory that contains those files. It works great if none of the files are open.
But if any file is open (i.e. index.txt
) , it is successfully deletes from directory and at the time of removing the directory it throws an exception like file is used by other application
.
Is there any way to close the open file in C# using p/invoke or anything else?
Upvotes: 1
Views: 212
Reputation: 11
The below code works great with .doc files.
But doesn't work with .txt file. It doesn't throw any exception for .txt Still searching for solution that works with .txt files.
I am opening files through Window Explorer, not via any code.
public static void Main()
{
String file;
file = "C:\\Temp\\test.doc";
bool b=IsCloseFile(file);
if (b)
MessageBox.Show("File Open");
}
public static bool IsCloseFile(string file)
{
FileStream stream = null;
try
{
stream = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException e)
{
return true;
}
finally
{
if (stream != null)
stream.Close();
}
return false;
}
}
Upvotes: 0
Reputation: 10708
Basically, the only way to break this link and be sure about it is to kill other processes from yours. There are various ways to do this, that have been pointed out, but a better question is whether you should.
I recommend looking into a try
-catch
pattern and making your application report the error to the user, instead of aggressively trying to delete a document which may be open for a very good reason from the perspective of the user or even the system itself.
Also note that killing outside processes is not a garuanteed solution, as there are multiple cases where the "kill outside process" step could fail (targeted process is run as Administrator and your app isn't, targeted process it set up as a Windows Service and restarts itself before you finish deletion, targeted process is a system-critical process which can't be terminated, ect.)
Upvotes: 0
Reputation: 4321
If you have noticed, when you open a MS Office file it creates a "shadow" file nearby - that is something like in RAM stored document. So if you delete the real file the "shadow" file remains in directory. So the RAM uses your directory.
In other words I think it is not possible to do it in C#.
Upvotes: 0
Reputation: 10984
The only way to delete files currently held open by other applications is to have those applications release the lock on the file (usually by closing the file) or by terminating the application itself.
Obviously, forcing an external application to terminate in order to delete a file that the app is currently holding open can often be a recipe for disaster!
Upvotes: 3