Copy file to a different directory

前端 未结 7 1898
暖寄归人
暖寄归人 2021-02-05 01:23

I am working on a project where I want to copy some files in one directory to a second already existing directory.

I can\'t find a way to simply copy from one folder to

7条回答
  •  离开以前
    2021-02-05 01:57

    If the destination directory doesn't exist, File.Copy will throw. This version solves that

    public void Copy(
                string sourceFilePath,
                string destinationFilePath,
                string destinationFileName = null)
    {
           if (string.IsNullOrWhiteSpace(sourceFilePath))
                    throw new ArgumentException("sourceFilePath cannot be null or whitespace.", nameof(sourceFilePath));
           
           if (string.IsNullOrWhiteSpace(destinationFilePath))
                    throw new ArgumentException("destinationFilePath cannot be null or whitespace.", nameof(destinationFilePath));
           
           var targetDirectoryInfo = new DirectoryInfo(destinationFilePath);
    
           //this creates all the sub directories too
           if (!targetDirectoryInfo.Exists)
               targetDirectoryInfo.Create();
    
           var fileName = string.IsNullOrWhiteSpace(destinationFileName)
               ? Path.GetFileName(sourceFilePath)
               : destinationFileName;
    
           File.Copy(sourceFilePath, Path.Combine(destinationFilePath, fileName));
    }
    

    Tested on .NET Core 2.1

提交回复
热议问题