2017-02-20 76 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

相关问题