开发者

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

How to copy all *.bak开发者_Python百科 files from Directory A to 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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜