2017-02-20 70 views
0

,當我想創建一個新的文件夾 我的工作我沒有問題檢查文件和創建文件夾和移動文件在C#

Directory.CreateDirectory

現在,我試圖讓從我的桌面上的所有圖像文件,我想所有圖像移動到與Directory.CreateDirectory

我已經testet file.MoveTo 從這裏

創建該文件夾

到這裏

file.MoveTo(@"C:\Users\User\Desktop\folder\test.txt"); 

這完美的作品。 現在我想這樣做,從我dekstop

(Directory.CreateDirectory(@"C:\Users\User\Desktop\Images");) 

所有圖像文件,我怎麼能這樣做呢?

+0

的可能的複製[如何遞歸地列出在C#中的目錄下的所有文件?(http://stackoverflow.com/問題/ 929276 /如何對recursi vely-list-all-the-files-in-a-directory-in-c) –

+0

Directory.GetFiles ok,但我想將所有圖像從桌面移動到桌面上的新建文件夾 – newatstackoverflow

+1

那麼,確定哪些文件存在與您的標準匹配(例如某些文件擴展名)並移動它們。什麼東西阻止你? –

回答

1

請試試這個:
您可以在一個特定的目錄過濾文件,然後在搜索結果德路移動的每個文件,你也許可以修改搜索模式來匹配多個不同的圖像文件格式

從一個根文件夾獲得一定的一些推廣的圖像
var files = Directory.GetFiles("PathToDirectory", "*.jpg"); 
    foreach (var fileFound in files) 
    { 
     //Move your files one by one here 
     FileInfo file = new FileInfo(fileFound); 
     file.MoveTo(@"C:\Users\User\Desktop\folder\" + file.Name); 
    } 
+0

謝謝!這是我需要的。 – newatstackoverflow

+0

但我用var files = Directory.GetFiles(@「C:\ Users \ User \ Desktop」,「* .jpg」)來試用它。 foreach(var file在文件中找到) { //在這裏一個一個地移動文件 FileInfo file = new FileInfo(fileFound); file.MoveTo(@「C:\ Users \ User \ Desktop \ Images」); }我得到一個錯誤 – newatstackoverflow

+0

你得到了什麼樣的錯誤?你能把它粘貼在評論中嗎? –

2

示例代碼:

 static void Main(string[] args) 
     { 
     // path to desktop 
     var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); 

     //get file extentions by speciging the needed extentions 
     var images = GetFilesByExtensions(new DirectoryInfo(desktopPath) ,".png", ".jpg", ".gif"); 

     // loop thrue the found images and it will copy it to a folder (make sure the folder exists otherwise filenot found exception) 
     foreach (var image in images) 
     { 
      // if you want to move it to another directory without creating a copy use: 
      image.MoveTo(desktopPath + "\\folder\\" + image.Name); 

      // if you want to move a copy of the image use this 
      File.Copy(desktopPath + "\\"+ image.Name, desktopPath + "\\folder\\" + image.Name, true); 
     } 
     } 

    public static IEnumerable<FileInfo> GetFilesByExtensions(DirectoryInfo dir, params string[] extensions) 
    { 
     if (extensions == null) 
      throw new ArgumentNullException("extensions"); 

     var files = dir.EnumerateFiles(); 
     return files.Where(f => extensions.Contains(f.Extension)); 
    } 
+0

謝謝你的男人!我這是我的意思...我沒有得到任何錯誤,但我的文件夾仍然是空的,爲什麼? – newatstackoverflow

+0

對不起,我沒有使用字符串searchPattern =「* .bmp」+「* .jpg」; – newatstackoverflow

+0

我用字符串searchPattern =「* .bmp」+「* .jpg」再次嘗試過它; FileInfo file = new FileInfo(img);這個字符串是在Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),searchPattern)中的字符串img。 file.MoveTo(@「C:\ Users \ User \ Desktop \ Images」); }我的文件夾仍然是空的我不知道爲什麼 – newatstackoverflow

相關問題