2016-10-12 33 views
0

我想根據名稱將文件從一個文件夾移動到另一個文件夾。 我想實現的是,我只從我的導出文件夾中選擇這些特定的文件,並將其替換到我的目標文件夾中。目標文件夾中的項目是關鍵,所以我只需要這些文件,否則如果文件已存在於目標文件夾中,請將其替換。根據名稱使用C#移動和替換文件

private static void CopyPaste() 
{ 
    var pstFileFolder = "C:/Users/chnikos/Desktop/CopyFolderTest/"; 
    var searchPattern = "*.docx"; 
    var soruceFolder= "C:/Users/chnikos/Desktop/CopyFolderTest/Test/"; 

    // Searches the directory for *.pst 
    foreach (var file in Directory.GetFiles(pstFileFolder, searchPattern)) 
    { 
     // Exposes file information like Name 
     var theFileInfo = new FileInfo(file); 
     // Gets the user name based on file name 
     // Sets up the destination location 
     var destination = soruceFolder+ theFileInfo.Name; 
     File.Move(file, destination); 
    } 
} 

源目標是:soruceFolder產地是:pstFileFolder

,我面對的是,我無法控制複製看來我的代碼是獲取所有文件,而不是問題檢查是否在sourfolder這些文件存在

+0

您能描述一下您使用此代碼時遇到的問題嗎?尤其是。目前還不清楚目標目標和源目標是什麼 – Steve

+0

在你的問題中沒有問題!你能解釋你有什麼問題嗎? –

+1

你可能想閱讀[如何調試小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) –

回答

2

您需要檢查的目標文件夾,看它是否包含你的文件象下面這樣:

private static void CopyPaste() 
{ 
var pstFileFolder = "C:/Users/chnikos/Desktop/CopyFolderTest/"; 
var searchPattern = "*.docx"; 
var soruceFolder= "C:/Users/chnikos/Desktop/CopyFolderTest/Test/"; 

// Searches the directory for *.pst 
foreach (var file in Directory.GetFiles(pstFileFolder, searchPattern)) 
{ 
    // Exposes file information like Name 
    var theFileInfo = new FileInfo(file); 
    // Gets the user name based on file name 
    // Sets up the destination location 
    var destination = soruceFolder+ theFileInfo.Name; 
    if(File.Exist(destination)) 
    { 
     File.Delete(destination); 
    File.Move(file, destination); 
    } 
} 
} 

它刪除目標文件夾中的文件(如果存在並移動文件)。所以如果文件不存在於目標文件夾中,它不會執行任何操作;)

+0

感謝分配,工作正常:) –

相關問題