How to copy a file over a network that is often used?

I need to copy a large file (about 20 MB) over the network. This is usually not a problem, but the file is written quite often (about once per second) by the application, which is in the same field as the file.

Since the file is written quite often, the call File.Copyis often interrupted. I also tried File.ReadAllLines, which seems to work every time, but takes forever.

Is there a better, more efficient, and safer way to copy a file over the network?

PS The file is written by a process that uses Log4Net. And, in case someone wonders, the process that makes the letter is not in my hands.

+5
source share
7 answers

fileshare , , , , , , , , r/w fileshare, . , , , , , , , .

+1

, File.Copy .

, File.Move . ,

for (int i = 0; i < 10; i++)
{
    try {
        File.Move(logFilePath, tempPathOnRemoteServer);
    } catch (Exception) { 
        if (i == 9)
            throw new Exception("Could not acquire lock");
        System.Threading.Thread.Sleep(1000 * (i+1)); }
}
File.Copy(tempPathOnRemoteServer, endPathOnLocalHost);

, , , .

, , , , File.Move File.Copy, , .

+1

FileStream FileAccess FileShare .

FileStream(String, FileMode, FileAccess, FileShare)
+1

:

string pathToFile = "path-to-your-file" ;
using ( Stream     s = File.Open( pathToFile , FileMode.Open , FileAccess.Read , FileShare.ReadWrite ) )
using ( TextReader r = new StreamReader( s ) )
{
    string fileContents = r.ReadToEnd() ;
    process( fileContents ) ;
}

, , , SOL.

, , , :

P.S. , Log4Net. , , - , , , .

, , Log4Net Appender, FileAppender RollingFileAppender?

, - FileAppender.ExclusiveLock, , IIRC, - .

( ?), ( ), Log4Net. Log4Net , . :

, .

, , , log4net, .

  • .
  • ( )
  • , .
  • repeat, ad nauseum, from # 4

.

+1

, , . , , :

:

using (var fin = File.Open(InputFilename, FileMode.Open, FileAccess.Read, FileShare.None))
{
    using (var fout = File.OpenWrite(OutputFilename))`
    {
        int bytesRead = 0;
        var buffer = new byte[65536];
        while ((bytesRead = fin.Read(buffer, 0, buffer.Length)) > 0)
        {
            fout.Write(buffer, 0, bytesRead);
        }
    }
}

, , Log4Net , , . .

, Log4Net , ( ). Log4Net , , ...

, . Log4Net , . . Log4Net , Log4Net .

.

, 20 . .

0

Well, then another option will always write in two files simulatively. One is real, and the other with a temporary name (let’s GUID). As soon as you need to copy, stop writing to a temporary file (instead, create a new one and continue writing there). Then the file will no longer be locked, so you can download it as slowly as you want. Only after - delete it.

0
source

How to make the first copy of the copy locally - which will be very fast and save its state, then download the copy and delete the copy at the end?

-1
source

All Articles