开发者

How to delete a file while some other thread is writing into it?

I am getting IOException whenever I try to use File.Delete method on a file into which some other thread i开发者_JS百科s writing. I don't have control over the writing thread. So from my thread how can I stop the file writing and delete the file.


You can't; that's the whole point of file locking - to prevent precisely what you are proposing.

The only way you can possibly achieve the same effect is to kill the other process first. That's a really bad design, and it may not be acceptable at all for you to do.

Why do you need to do this, anyway?


For this to be possible, the writing thread has to open the file in a non-exclusive mode that would allow access to the file to others.

If you have no control whatsoever on the writing thread, you won't be able to do it.

A potential alternative is to try to get the same handle that is being used for writing. After all if it's a thread in your application then this handle is somewhere in your memory space.

Remember that if you do manage to delete the file, the other thread might not expect it and if it doesn't handle the exception it will get when trying to write again, your entire process may be terminated.

Seriously it sounds like you should reconsider your design.


Simply , that is not possible since some other process is having exclusive lock on the file while writing and forcefully , you can not acquire lock.

So either your process has to wait until locking process releases the lock or somehow kill the locking process.


Some other thread? I.e. in your own program?

Communicate to it that something has come up and it needs to stop writing, close the file and delete it. Then let it respond to the message and do so.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜