简体   繁体   中英

How do i copy files from one directory to another directory?

string[] s = Directory.GetFiles(t, "*.txt",SearchOption.AllDirectories);
for (int i = 0; i < s.Length; i++)
{
    File.Copy(s[i],
}

File.Copy will copy the files to another file name. I want to keep the same files names just copy them from one directory to another directory.

用这个:

 File.Copy(s[i], "c:\\anotherFolder\\" + Path.GetFileName(s[i]));

You can do it nicely like this:

Directory.GetFiles("c:\\temp", "*.txt", SearchOption.AllDirectories) // get the files
    .Select(c => new FileInfo(c)) // project each filename into a fileinfo
    .ToList() // convert to list
    .ForEach(c => c.CopyTo("d:\\temp\\" + c.Name)); // foreach fileinfo, copy to the desired path + the actual file name

You could view this post, which should help;

Or this MSDN link:

Code snippet:

var sourceDir = @"c:\sourcedir";
var destDir = @"c:\targetdir";
var pattern = "*.txt";

foreach (var file in new DirectoryInfo(sourceDir).GetFiles(pattern))
{
   file.CopyTo(Path.Combine(destDir, file.Name));
}

Hope this helps?

You are doing it the right way..

See example from microsoft

http://msdn.microsoft.com/en-us/library/bb762914.aspx

another solution might be to call the xcopy command ...

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