4

すべての形式のファイル(.txt、.pdf、.doc ...)ファイルをソースフォルダーから宛先にコピーしようとしています。

テキストファイル専用のコードを書いています。

すべてのフォーマットファイルをコピーするにはどうすればよいですか?

私のコード:

string fileName = "test.txt";
string sourcePath = @"E:\test222";
string targetPath =  @"E:\TestFolder"; 

string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);

ファイルをコピーするコード:

System.IO.File.Copy(sourceFile, destFile, true);
4

3 に答える 3

10

Directory.GetFilesを使用して、パスをループします

string sourcePath = @"E:\test222";
string targetPath =  @"E:\TestFolder";

foreach (var sourceFilePath in Directory.GetFiles(sourcePath))
{
     string fileName = Path.GetFileName(sourceFilePath);
     string destinationFilePath = Path.Combine(targetPath, fileName);   

     System.IO.File.Copy(sourceFilePath, destinationFilePath , true);
}
于 2012-06-07T07:54:45.213 に答える
5

ちょっと、拡張してフィルタリングしたいという印象を受けました。もしそうなら、これはそれを行います。そうでない場合は、以下に示す部分をコメントアウトしてください。

string sourcePath = @"E:\test222";
string targetPath =  @"E:\TestFolder"; 

var extensions = new[] {".txt", ".pdf", ".doc" }; // not sure if you really wanted to filter by extension or not, it kinda seemed like maybe you did. if not, comment this out

var files = (from file in Directory.EnumerateFiles(sourcePath)
             where extensions.Contains(Path.GetExtension(file), StringComparer.InvariantCultureIgnoreCase) // comment this out if you don't want to filter extensions
             select new 
                            { 
                              Source = file, 
                              Destination = Path.Combine(targetPath, Path.GetFileName(file))
                            });

foreach(var file in files)
{
  File.Copy(file.Source, file.Destination);
}
于 2012-06-07T08:05:51.870 に答える
2
string[] filePaths = Directory.GetFiles(@"E:\test222\", "*", SearchOption.AllDirectories);

これを使用して、すべてのファイルをループして宛先フォルダーにコピーします

于 2012-06-07T07:59:18.970 に答える