简体   繁体   中英

C# Copy file or folder

I am trying to write a program to keep multiple folders in sync. To do this, I need to copy and delete files and subfolders.

To me, it doesn't make a difference if an object is a file or a folder, I want to create all necessary parent folders and copy the object, overwriting if necessary. I'm currently using a jagged array of FileSystemInfo to hold my files/folders.

This has the advantage of avoiding a duplication of code to sync files and folders separately.

However, I can't figure out how to Copy a FileSystemInfo. I'm looking for a way to be able to copy/delete/read creation or modified time that will work on both files and folders.

FileSystemInfo don't have Copy or Delete methods but is the base class for DirectoryInfo and FileInfo.

So when you loop over your FileSystemInfo objects you have to cast to the proper concrete class and use the specific copy/delete methods.

foreach( var fsi in fileSystemInfoObjects )
{
     if( fsi is DirectoryInfo )
     {
        var directory =  (DirectoryInfo)fsi;
        //do something
     }
     else if (fsi is FileInfo )
     {
        var file = (FileInfo)fsi;
        //do something
     }
}

I used sam's answer to help me solve my problem. What I did was put the copying logic in my custom class so that I don't need to duplicate the logic whenever I use it in my code.

public class myFSInfo
{
    public FileSystemInfo Dir;
    public string RelativePath;
    public string BaseDirectory;
    public myFSInfo(FileSystemInfo dir, string basedir)
    {
        Dir = dir;
        BaseDirectory = basedir;
        RelativePath = Dir.FullName.Substring(basedir.Length + (basedir.Last() == '\\' ? 1 : 2));
    }
    private myFSInfo() { }
    /// <summary>
    /// Copies a FileInfo or DirectoryInfo object to the specified path, creating folders and overwriting if necessary.
    /// </summary>
    /// <param name="path"></param>
    public void CopyTo(string path)
    {
        if (Dir is FileInfo)
        {
            var f = (FileInfo)Dir;
            Directory.CreateDirectory(path.Substring(0,path.LastIndexOf("\\")));
            f.CopyTo(path,true);
        }
        else if (Dir is DirectoryInfo) Directory.CreateDirectory(path);
    }
}

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