2

I am trying to figure out why the following code prevents overwriting of the file used in the filestream.

This only happens when using Cut and Paste, Copy and Paste works weirdly enough

var fs = new FileStream(
    File.OpenHandle(
        path,
        mode: FileMode.Open,
        access: FileAccess.Read,
        share: FileShare.Delete | FileShare.ReadWrite
        ), FileAccess.Read);

This is the error shown when Using Cut & Paste enter image description here

This snippet demonstrates the error:

Both files exist, no other applications are using them either

var path = @"C:\temp\test\test.log";
var pathCopy = @"C:\temp\test.log";

var fs = new FileStream(
    File.OpenHandle(
        path,
        mode: FileMode.Open,
        access: FileAccess.Read,
        share: FileShare.Delete | FileShare.ReadWrite
        ), FileAccess.Read);
    

File.Copy(pathCopy, path,true); //Works
File.Move(pathCopy, path, true); //Does NOT work -> AccessError
Daniel
  • 99
  • 8
  • because you don't have write access? – Jodrell Nov 29 '22 at 08:11
  • File.Copy or move are not using the created FileStream, this is just to demonstrate that other applications are not able to use Cut & paste but can Copy & paste over the file – Daniel Nov 29 '22 at 08:25
  • yeah, I get that and your should probably remove superfluous code from question. However, do you have write access to the destination, does the destination exist? – Jodrell Nov 29 '22 at 08:28
  • 1
    @Jodrell There is no superfluous code here, having that file handle open causes the issue in question (assuming both `path` and `pathCopy` already exist). – Evk Nov 29 '22 at 08:30
  • I have updates the code to be more clear about my issue (hopefully). Also playing around with the different flags yielded no change in behavior yet – Daniel Nov 29 '22 at 08:46
  • Does `File.Delete` work? I'm not sure how much I would trust `FileShare.Delete`, I would not be completely chocked if it has some edge cases or undocumented behavior. – JonasH Nov 29 '22 at 08:51
  • Why not close the handle, dispose of the filestream object? – Harsh Nov 29 '22 at 08:56
  • If you are running on Windows, this is the documentation for the underlying API, that may still be used, https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea – Jodrell Nov 29 '22 at 09:04
  • File.Delete works as expected. The issue seems specific to File.Move with Overwrite = true But my issue is that the file move in Explorer will not work - the code above is just demonstration – Daniel Nov 29 '22 at 09:26
  • SafeFileHandle on its own wont work for me. https://i.imgur.com/vtHL0HZ.png – Daniel Nov 29 '22 at 09:40

0 Answers0