Does File.Copy prevent another app from writing to the file?
Asked Answered
D

2

7

I want to copy some text files, that are written by another app, but I don't want to do anything to prevent the other app. from writing to these files.

I am using File.Copy, from the System.IO namespace, C#, .Net Framework 2.0.

I checked MSDN's documentation, but nothing is specifically stated about the method that File.Copy uses. Is it a wrapper to an unmanaged API call?

Does File.Copy lock, or block the file being copied in any way?

Thanks in advance for any info about this.

Danell answered 26/11, 2011 at 9:31 Comment(1)
@Joey: I assume that Matt is referring to the source file, not the target file. Still, copying a file while another process is writing to it could possibly lead to odd results, depending on what kind of file it is, and the purpose of copying it.Beardsley
P
1

You can use .Net Reflector (or other decompile tool) to look at internal structure of the method.

Actually you can see that System.IO File.Copy uses Microsoft.Win32.Win32Native library for coping files. Microsoft.Win32.Win32Native it is CLR wrapper for all Win32 native operations.

Philipp answered 26/11, 2011 at 11:19 Comment(2)
Thanks everyone for your replies.Danell
Joey, yes I am refering to the source file, and not the target file I am copying to. Schglurps, I have expiremented with this, I opened a filestream with fileshare set to None in another app. and I was able to copy the file anyway, using File.Copy. Sailer, thanks. I don't know why I did not think of this. I will look at the method in reflector, and read up on the win32 api call.Danell
L
2

If the other app creates its files by specifying FileShare.None, you will receive an UnauthorizedAccessException. So I imagine that you just have to process this specific exception in your app.

Licketysplit answered 26/11, 2011 at 9:52 Comment(0)
P
1

You can use .Net Reflector (or other decompile tool) to look at internal structure of the method.

Actually you can see that System.IO File.Copy uses Microsoft.Win32.Win32Native library for coping files. Microsoft.Win32.Win32Native it is CLR wrapper for all Win32 native operations.

Philipp answered 26/11, 2011 at 11:19 Comment(2)
Thanks everyone for your replies.Danell
Joey, yes I am refering to the source file, and not the target file I am copying to. Schglurps, I have expiremented with this, I opened a filestream with fileshare set to None in another app. and I was able to copy the file anyway, using File.Copy. Sailer, thanks. I don't know why I did not think of this. I will look at the method in reflector, and read up on the win32 api call.Danell

© 2022 - 2024 — McMap. All rights reserved.