简体   繁体   中英

how to copy all *.bak files from Directory A to Directory B?

如何将所有*.bak文件从Directory A复制到Directory B

This should do what you need:

string dirA = @"C:\";
string dirB = @"D:\";

string[] files = System.IO.Directory.GetFiles(dirA);

foreach (string s in files) {
    if (System.IO.Path.GetExtension(s).equals("bak")) {
        System.IO.File.Copy(s, System.IO.Path.Combine(targetPath, fileName), true);
    }
}

I'm not going to give you the full solution, but check out Directory.GetFiles (which takes a search pattern) and File.Copy .

Those two methods are everything you need.

There's two ways, the pure C# way:

var items = System.IO.Directory.GetFiles("Directory A", "*.bak", System.IO.SearchOption.TopDirectoryOnly);
foreach(String filePath in items)
{
    var newFile = System.IO.Path.Combine("Directory B", System.IO.Path.GetFileName(filePath));
    System.IO.File.Copy(filePath, newFile);
}

The robocopy way:

var psi = new System.Diagnostics.ProcessStartInfo();
psi.FileName = @"C:\windows\system32\robocopy.exe";
psi.Arguments = "Directory A Directory B *.bak";
System.Diagnostics.Process.Start(psi);

use this link http://www.codeproject.com/KB/cs/Execute_Command_in_CSharp.aspx

to execute

xcopy /y /f PathOfA\*.bak PathOfB\

My improvement on above suggestions:

public static void CopyFilesWithExtension(string src, string dst, string extension)
{
    string[] files = System.IO.Directory.GetFiles(src);

    foreach (string s in files)
    {
         if (System.IO.Path.GetExtension(s).Equals(extension))
         {
             var filename = System.IO.Path.GetFileName(s);
             System.IO.File.Copy(s, System.IO.Path.Combine(dst, filename));
         }
    }
}

Usage:

Utils.CopyFilesWithExtension(@"C:\src_folder",@"C:\dst_folder",".csv");

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