当我想创建一个新文件夹时,我没有任何问题 我正在使用
Directory.CreateDirectory
现在我正在尝试从我的桌面获取所有图像文件,并且我想将所有图像移动到使用Directory.CreateDirectory创建的文件夹
我已经测试过.MoveTo 从这里
FileInfo file = new FileInfo(@"C:\Users\User\Desktop\test.txt");
到这里
file.MoveTo(@"C:\Users\User\Desktop\folder\test.txt");
这很完美。 现在我想用我的dekstop
中的所有图像文件来做这件事(Directory.CreateDirectory(@"C:\Users\User\Desktop\Images");)
我怎么能这样做?
答案 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));
}
答案 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);
}