简体   繁体   中英

C# Move Files From A Folder To Another (How to code: if doesn't exist do nothing)

Beginner: Here is my code:

using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;   

public void MoveFiles(string sourcePath, string destinationPath)
    {
        string[] files = Directory.GetFiles(sourcePath);
        Parallel.ForEach(files, file =>
        {
                if ("HOW TO CODE: If the sourceFiles exist in destFolder")
                {
                    File.Move(file, Path.Combine(destinationPath, Path.GetFileName(file)));
                }
        });
    }

I get an error if the source files exist in destination folder. How can I correct that and is there a better way to do that?

File has the static methods Delete and Exists you can use for that very case

if(File.Exists(file))
{
    if(File.Exists(destinationFile))
    {
        File.Delete(destinationFile);
    }
    File.Move(file, destinationFile);
}

I've used destinationFile to avoid redundancy.

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