Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Copy a File That is Being Written To

Tags:

c#

copy

I have read many other posts about this topic, but none appear to solve my problem directly (which surprises me).

Regardless...I wrote a log parser and very simply I am looking to copy a file from a remote machine locally, prior to parsing it. The file I am trying to copy is being written to constantly and I have ‘random’ success in copying it. Sometimes it will work and other times I will get an ‘access is denied’ or FileAccess error. A few other points:

  • Whenever I use windows explorer to copy the file locally, I never
    have a problem copying it (which leads me to believe it’s perfectly
    possible to copy the file 100% of the time).
  • I can always open the file using a text editor in its remove location.
  • I do not own the file being written to and do not wish to ‘lock’ it in anyway such that the application that is actually writing to this file fails.

Does anyone have any suggestions for how to copy this file?

The current command I am using is:

File.Copy(this.txt_log_file_to_analyze.Text, sLogFileToAnalyze,true);
like image 690
user2786756 Avatar asked Nov 30 '25 08:11

user2786756


1 Answers

I guess you'll have to open the file using:

File.Open(this.txt_log_file_to_analyze.Text,FileMode.Open,FileAccess.Read,FileShare.ReadWrite)

and then copy the contents of the file 'manually' i.e.

using (var from = File.Open("path", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var to = File.OpenWrite("to_path"))
{
    from.CopyTo(to);
}

or if .NET 4.5 see How do I copy the contents of one stream to another?

Using the above api, you can specify that you do not want exclusive access to the file.

like image 145
Rudi Avatar answered Dec 02 '25 22:12

Rudi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!