簡體   English   中英

C#將文件從本地計算機復制到遠程共享失敗

[英]C# Copying files from local machine to remote share failed

我以簡單的方式將xml文件從本地計算機復制到遠程共享

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);

我注意到有時復制意外結束於文件中間。 因此,我必須比較源文件和目標文件,以確保它已被完全復制。

沒有這樣的比較,如何強制成功復制?

文件復制的一般原因是超時,拒絕訪問或網絡中斷。 嘗試在復制操作1周圍進行嘗試捕獲,以識別兩次停止之間的原因。 如果您可以對另一個本地文件夾執行相同的操作,然后成功啟動復制到網絡,則唯一的原因可能是網絡不穩定。 嘗試使用一個很小的文件(一些KB)來查看操作是否成功。 這將嘗試解決由於文件大小而引起的超時問題。

對於非常大的文件,您必須設置一個發件人和收件人的應用程序。 您可以按照此MSDN帖子https://blogs.msdn.microsoft.com/webapps/2012/09/06/wcf-chunking/中的說明使用WCF Chunking或Streaming。

我建議比較源文件和目標文件的校驗和,以了解復制是否成功。 如果不成功,則可以根據要求采用不同的策略重試或快速執行故障轉移。

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);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM