简体   繁体   English

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

[英]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 . 我不会为您提供完整的解决方案,但请查看Directory.GetFiles (采用搜索模式)和File.Copy

Those two methods are everything you need. 这两种方法是您所需要的。

There's two ways, the pure C# way: 有两种方法,纯C#方法:

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: robocopy方式:

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 使用此链接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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM