Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing closed an open file by C#

I found a similar question here but it was closed/accepted with an answer of "don't do that".

I'm in a situation where I don't care what happens to the other applications, I want to take a file that may be locked by others (rudely if needed) and have my way with it. I may need to move, rename, or delete this file.

Basically I need to process files in a directory that is created by an app that doesn't clean up it's locks. I know the app is done processing when mine calls, but I need to kill the locks when I run. In addition it seems I'm conflicting with reads from local AV software scanning the remote share where the server is.

All this adds up to an unresolvable "force close" situation so I can do what I need. Does anyone have an idea on what to do?

like image 458
makerofthings7 Avatar asked Aug 19 '10 22:08

makerofthings7


People also ask

Does C automatically close files?

It will close any files you left open when it terminates your process, and perform any other cleanup that is necessary (e.g. if a file was marked delete-on-close, it will delete the file then; note that that sort of thing is platform-specific). However, another issue to be careful of is buffered data.

How do you close a file in C?

Closing a file is performed using the fclose() function. fclose(fptr); Here, fptr is a file pointer associated with the file to be closed.

Which function is used to close all opened files in C?

C provides a number of build-in function to perform basic file operations: fopen() - create a new file or open a existing file. fclose() - close a file. getc() - reads a character from a file.

How do you close a file that is open in system?

By right click on the wanted file, choose an option, “Close open file”, and that will close it.


2 Answers

First you can use this post to verify that it's the dodgy app that's locking them:

How do I find out which process is locking a file using .NET?

Then this post outlines a way to close them:

http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/04a1e899-2a38-4d95-8ed5-6d53344e4d76

like image 111
SteveCav Avatar answered Sep 28 '22 00:09

SteveCav


This is probably irrelevant and if it is please someone comment but there was a work-around I've used in explorer before to get around file locks.
If a file was locked by a process that had died Windows often wouldn't let you delete it but if you created a new file of the same name somewhere else, moved it to the folder it would succeed. You could then delete the new file and all was well.
To use this for your app you'd have to be able to read the file and hold it in memory before you did this then you write it back out after you'd got rid of the old one.
Maybe it will help, maybe not but it's worth trying.

like image 27
Daniel Avatar answered Sep 28 '22 00:09

Daniel