How to safely copy file while another app writing in it, make sure both program not crash

后端 未结 2 693
甜味超标
甜味超标 2021-01-16 06:29

I am managing a 3rd party vendor application which creates .txt files and write user logs into this .txt file, there are total of 10 log files, each has max size of 100 mb,

2条回答
  •  时光说笑
    2021-01-16 07:00

    Try reading and writing bytes instead of using the File.Copy(...) method. It works for me in similar situations such as backing up shared local databases over networks. Hopefully it works for you.

    var srcPath = "SourcePath...";
    var desFile = "DestinationPath...";            
    var buffer = new byte[1024 * 1024];
    var bytesRead = 0;
    
    using (FileStream sr = new FileStream(srcPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (BufferedStream srb = new BufferedStream(sr))
    using (FileStream sw = new FileStream(desFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
    using (BufferedStream swb = new BufferedStream(sw))
    {
        while(true)
        {
            bytesRead = srb.Read(buffer, 0, buffer.Length);
            if (bytesRead == 0) break;
            swb.Write(buffer, 0, bytesRead);
        }
        swb.Flush();
    }
    

    Good day.

提交回复
热议问题