简体   繁体   中英

C# Copying files from local machine to remote share failed

I'm copying xml files from local machine to remote share with simple way

DataTable dt = new DataTable();

// composing dt

string file = "test.xml";
string path = Path.Combine(@"C:\local\path", file);
string path2 = Path.Combine(@"\\path\to\remote\share", file);

if (File.Exists(path2)) File.Delete(path2);
dt.WriteXml(path);
File.Copy(path, path2);

I've noticed that sometimes copying unexpectedly ends in the middle of the file. So I have to compare source and target file to be sure that it has been fully copied.

How to force successful copying without such comparing?

General causes in file copy is a timeout, access deny or network outage. Put a try-catch around copy operation 1st to identify the reason behind in-between stopping. If you can do the same operation to another local folder, and then successfully start copy to network, the only reason can be network instability. Try with a very small size file (some KBs) to see if the operation is successful. This will try to address the timeout issue due to file size.

For very large files, you have to setup a sender and reciever apps. You can use WCF Chunking or Streaming as described in this MSDN post https://blogs.msdn.microsoft.com/webapps/2012/09/06/wcf-chunking/

I would suggest comparing the check-sum of source and destination file to know whether the copy was successful or not. If unsuccessful, you may employ different strategies to either retry or fail-fast depending on what is the requirement.

class Program
{
    private string fileName = "myFile.xml";
    private string sourcePath = @"d:\source\" + fileName;        
    private string destinationPath = @"d:\destination\" + fileName;


    static void Main(string[] args)
    {           
        (new Program()).Run();
    }

    void Run()
    {
        PrepareSourceFile();
        CopyFile();
    }

    private void PrepareSourceFile()
    {
        DataTable helloWorldData = new DataTable("HelloWorld");            
        helloWorldData.Columns.Add(new DataColumn("Greetings"));
        DataRow dr = helloWorldData.NewRow();
        dr["Greetings"] = "Ola!";
        helloWorldData.Rows.Add(dr);
        helloWorldData.WriteXml(sourcePath);
    }

    private void CopyFile()
    {
        int numberOfRetries = 3; // I want to retry at least these many times before giving up.
        do
        {   
            try
            {
                File.Copy(sourcePath, destinationPath, true);
            }
            finally
            {
                if (CompareChecksum())
                    numberOfRetries = 0;
            }


        } while (numberOfRetries > 0);
    }


    private bool CompareChecksum()
    {
        bool doesChecksumMatch = false;
        if (GetChecksum(sourcePath) == GetChecksum(destinationPath))
            doesChecksumMatch = true;
        return doesChecksumMatch;
    }

    private string GetChecksum(string file)
    {
        using (FileStream stream = File.OpenRead(file))
        {
            SHA256Managed sha = new SHA256Managed();
            byte[] checksum = sha.ComputeHash(stream);
            return BitConverter.ToString(checksum).Replace("-", String.Empty);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM