簡體   English   中英

復制並覆蓋所有文件

[英]copy and overwrite all files

我有一些文件要復制到另一個文件夾,並覆蓋現有文件(如果存在)。 如果在復制過程中發生了一些事情並且所有文件都沒有被完全復制。 我怎么能確定,如果沒有復制任何文件,就不會復制任何文件?

DirectoryInfo dir = new DirectoryInfo(@"c:\myfiles");
FileInfo[] files = dir.GetFiles();
Foreeach (FileInfo file in files)
{
    string temppath = Path.Combine(@"c:\destinationfolder",file.name);
    file.CopyTo(temppath,true);
}

謝謝@Erno_de_Weerd 根據您的評論,我找到了這個 Nugget 包:

發送文件管理器

並基於此 Nugget 包,我將代碼更改為此,它正在工作

 public static async Task DirectoryMoveToAsync(string sourceDirName, string destDirName, bool copySubDirs)
        {
            // Get the subdirectories for the specified directory.
            DirectoryInfo dir = new DirectoryInfo(sourceDirName);

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException(
                    "Source directory does not exist or could not be found: "
                    + sourceDirName);

            }

            DirectoryInfo[] dirs = dir.GetDirectories();
            // If the destination directory doesn't exist, create it.
            if (!Directory.Exists(destDirName))
            {
                Directory.CreateDirectory(destDirName);
            }

            // Get the files in the directory and copy them to the new location.
            FileInfo[] files = dir.GetFiles();          


            // Wrap a file copy and a File Delete in the same transaction
            TxFileManager fileMgr = new TxFileManager();
            using (TransactionScope scope1 = new TransactionScope())
            {               
                int x = 0;
                foreach (FileInfo file in files)
                {
                    // Just for the test, what will happen to the files if an exception occurs
                    //*************************************************************
                    x++;
                    if (x == 10)
                    {
                        throw new FileNotFoundException();
                    }
                    //**************************************************************

                    string temppath = Path.Combine(destDirName, file.Name);                 
                    if (fileMgr.FileExists(temppath))
                    {
                        fileMgr.Delete(temppath);
                    }
                    fileMgr.Move(file.FullName, temppath);                
                }

                scope1.Complete();
            }


            // If copying subdirectories, copy them and their contents to new location.
            if (copySubDirs)
            {
                foreach (DirectoryInfo subdir in dirs)
                {
                   string temppath = Path.Combine(destDirName, subdir.Name);
                   await DirectoryMoveToAsync(subdir.FullName, temppath, copySubDirs);
                }
            }

        }


  private async void ButtonMove_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.Wait;
                await Task.Run(() => DirectoryMoveToAsync(@"Files", @"moved", false)); //"."
                MessageBox.Show("Moved");             
            }
            catch(Exception ex)
            {
                MessageBox.Show("Failed : " + ex.Message.ToString() );
            }
            finally
            {
                Cursor = Cursors.Arrow;
            }
        }

GetFiles 發生異常時將停止。 請參閱下面的代碼,其中包含允許您繼續的異常處理程序:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;

namespace WriteFileNamesXml
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        const string FOLDER = @"c:\temp";
        static XmlWriter writer = null;
        static void Main(string[] args)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            writer = XmlWriter.Create(FILENAME, settings);
            writer.WriteStartDocument(true);

            DirectoryInfo info = new DirectoryInfo(FOLDER);
            WriteTree(info);

            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();


        }
        static long WriteTree(DirectoryInfo info)
        {
            long size = 0;
            writer.WriteStartElement("Folder");
            try
            {
                writer.WriteAttributeString("name", info.Name);
                writer.WriteAttributeString("numberSubFolders", info.GetDirectories().Count().ToString());
                writer.WriteAttributeString("numberFiles", info.GetFiles().Count().ToString());
                writer.WriteAttributeString("date", info.LastWriteTime.ToString());


                foreach (DirectoryInfo childInfo in info.GetDirectories())
                {
                    size += WriteTree(childInfo);
                }

            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception Folder : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error", errorMsg);
            }

            FileInfo[] fileInfo = null;
            try
            {
                fileInfo = info.GetFiles();
            }
            catch (Exception ex)
            {
                string errorMsg = string.Format("Exception FileInfo : {0}, Error : {1}", info.FullName, ex.Message);
                Console.WriteLine(errorMsg);
                writer.WriteElementString("Error", errorMsg);
            }

            if (fileInfo != null)
            {
                foreach (FileInfo finfo in fileInfo)
                {
                    try
                    {
                        writer.WriteStartElement("File");
                        writer.WriteAttributeString("name", finfo.Name);
                        writer.WriteAttributeString("size", finfo.Length.ToString());
                        writer.WriteAttributeString("date", info.LastWriteTime.ToString());
                        writer.WriteEndElement();
                        size += finfo.Length;
                    }
                    catch (Exception ex)
                    {
                        string errorMsg = string.Format("Exception File : {0}, Error : {1}", finfo.FullName, ex.Message);
                        Console.WriteLine(errorMsg);
                        writer.WriteElementString("Error", errorMsg);
                    }
                }
            }

            writer.WriteElementString("size", size.ToString());
            writer.WriteEndElement();
            return size;

        }
    }
}

暫無
暫無

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

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