2013-08-02 2 views
2

Source и Target имеют те же подкаталоги, как это:C# копирование файлов из исходной папки в целевую папку

C: \ фс \ источник \ а \
C: \ фс \ источник \ б \

C: \ фс \ цель \ а \
C: \ фс \ цель \ б \

Я борется с копированием файлов из источника к цели, если не существующие файлы. Каков наилучший способ в C# сравнить исходные папки с целевыми папками - проверить, не будут ли целевые файлы не выходить, скопировать файлы из определенного источника (c: \ fs \ source \ a \ config.xml и app.config) в определенную цель (с: \ фс \ цель \ а \). Если целевые файлы существуют, игнорируйте его. Как написать его на C#?

Ваш пример кода очень ценится. Благодаря!

public void TargetFileCreate() 
    { 
     foreach (var folder in SourceFolders) 
     { 
      string[] _sourceFileEntries = Directory.GetFiles(folder); 

      foreach (var fileName in _sourceFileEntries) 
      { //dont know how to implement here: 
       //how to compare source file to target file to check if files exist or not 
       //c:\fs\source\A\config.xml compares to c:\fs\target\A\ (no files) that should be pasted 
       //c:\fs\source\B\config.xml compares to c:\fs\target\B\config.xml that is already existed - no paste 
      } 
     } 
    } 
+0

Я пытался искать в обеих петлях (Foreach) между исходными папками и целевыми папками, в которых можно сравнить определенную папку и проверить, если эта папка не имеет файлы, скопировать файлы из источника в эту папку. мой код кажется очень странным. Я бы хотел увидеть лучший способ кодирования ... – user235973457

ответ

0

Вы можете проверить для каждого файла, если он существует так:

string curFile = @"c:\temp\test.txt"; 
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist."); 

положить это внутри цикла. затем скопируйте эти файлы там.

MSDN КОД:

// Simple synchronous file copy operations with no user interface. 
// To run this sample, first create the following directories and files: 
// C:\Users\Public\TestFolder 
// C:\Users\Public\TestFolder\test.txt 
// C:\Users\Public\TestFolder\SubDir\test.txt 
public class SimpleFileCopy 
{ 
    static void Main() 
    { 
     string fileName = "test.txt"; 
     string sourcePath = @"C:\Users\Public\TestFolder"; 
     string targetPath = @"C:\Users\Public\TestFolder\SubDir"; 

     // Use Path class to manipulate file and directory paths. 
     string sourceFile = System.IO.Path.Combine(sourcePath, fileName); 
     string destFile = System.IO.Path.Combine(targetPath, fileName); 

     // To copy a folder's contents to a new location: 
     // Create a new target folder, if necessary. 
     if (!System.IO.Directory.Exists(targetPath)) 
     { 
      System.IO.Directory.CreateDirectory(targetPath); 
     } 

     // To copy a file to another location and 
     // overwrite the destination file if it already exists. 
     System.IO.File.Copy(sourceFile, destFile, true); 

     // To copy all the files in one directory to another directory. 
     // Get the files in the source folder. (To recursively iterate through 
     // all subfolders under the current directory, see 
     // "How to: Iterate Through a Directory Tree.") 
     // Note: Check for target path was performed previously 
     //  in this code example. 
     if (System.IO.Directory.Exists(sourcePath)) 
     { 
      string[] files = System.IO.Directory.GetFiles(sourcePath); 

      // Copy the files and overwrite destination files if they already exist. 
      foreach (string s in files) 
      { 
       // Use static Path methods to extract only the file name from the path. 
       fileName = System.IO.Path.GetFileName(s); 
       destFile = System.IO.Path.Combine(targetPath, fileName); 
       System.IO.File.Copy(s, destFile, true); 
      } 
     } 
     else 
     { 
      Console.WriteLine("Source path does not exist!"); 
     } 

     // Keep console window open in debug mode. 
     Console.WriteLine("Press any key to exit."); 
     Console.ReadKey(); 
    } 
} 
2
foreach (var file in Directory.GetFiles(source)) 
{ 
    File.Copy(file, Path.Combine(target, Path.GetFileName(file)), false); 
} 
0
foreach (var file in Directory.GetFiles(source)) 
{ 
    var targetFile = System.IO.Path.Combine(target, System.IO.Path.GetFileName(file)); 
    if(!File.Exists(targetFile)) 
    { 
     File.Copy(file, targetFile) 
    } 
} 
Смежные вопросы