Moving and overwriting a C # file

I am developing a multi-threaded application. I am somewhere in my code:

File.Delete(sidetapedata); File.Move(sidetapedata2, sidetapedata); //sidetapedata and sidetapedata2 are two file paths that correspond to sidetapedata.txt and sidetaptdata2.txt in some directory. 

The second line sometimes works fine at other times, it throws an IOException :

 Cannot create a file when that file already exists. 

There is another stream that accesses the sidetapedata file, but that only reads this file, does not perform write operations. i am using locks to protect race conditions. I don’t know why this is happening.

UPDATE : even when the visual C # debugger shows me this exception, looking at the directory containing these files, I see that there is no sidetapedata.txt file, but there is a sidetapedata2.txt file!

UPDATE2 . In addition, this behavior only occurs when sidetapedata.txt and sidetapedata2.txt are empty

+4
source share
3 answers

I don’t know why this will happen if any event caused by the Delete call does not occur on the file system, which means that it will not actually be deleted until it is returned after the call. Several variants:

  • You can execute a cycle (with some maximum number of cycles before the error), where you check the existence of the file before trying to move and sleep for a while if it still exists after deletion.
  • You can use File.Copy(sidetapedata, sidetapedata2, true) to copy instead of moving, and then delete the original file. This will be less efficient, though, assuming that the move will be handled by simply changing the entry in the file system directory (rather than actually copying the data).
  • You can use File.Move in the target file instead of File.Delete to transfer it to another safe different file name and then delete it, hoping that Move more atomic than Delete .

I suspect that the thread here does not matter - I suggest you write a short but complete program to test it so that you can exclude it (and easily check for workarounds).

+7
source

I'm not sure if this is the same for .NET, but according to win32 DeleteFile api link:

The DeleteFile function marks a file for deletion when closing. Therefore, file deletion does not occur until the last file descriptor is closed.

Thus, there is a possibility that the time between calling Delete return and Windows closes the last file descriptor. It looks like you are calling Move over this period of time.

+3
source

According to this answer : use FileStream with FileShare

 FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None); 
0
source

Source: https://habr.com/ru/post/1389880/


All Articles