我正在创建C#控制台应用程序以清理Windows中的下载文件夹 我的应用程序适用于视频文件和移动,并从下载文件夹中删除它。但是如何在子文件夹中获取文件并将其添加到我的文件数组中呢?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace CleanDownloadFolder
{
class Program
{
static void Main(string[] args)
{
string sourcePath = @"C:\Users\___\Downloads";
string targetPath = @"C:\Users\__\Videos";
CopyDirectory(sourcePath, targetPath);
}
private static void CopyDirectory(string sourcePath, string targetPath)
{
// 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);
}
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
string fileName = null;
string destFile = null;
// 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);
if (Path.GetExtension(fileName) == ".avi")
{
System.IO.File.Copy(s, destFile, true);
System.IO.File.Delete(s);
}
}
}
}
}
}
答案 0 :(得分:1)
Directory.GetFiles有一个重载,可用于获取子目录中的文件列表
string[] files = Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories);
您的代码的其余部分应该按原样运行,但是,如果您只对AVI文件感兴趣,那么您可以将该扩展直接放在GetFiles调用中。通过这种方式,您只能获得AVI文件,并且可以简化您的代码,删除if
string[] files = Directory.GetFiles(sourcePath. "*.AVI", SearchOption.AllDirectories);
string fileName = null;
string destFile = null;
// 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 = Path.GetFileName(s);
destFile = Path.Combine(targetPath, fileName);
File.Copy(s, destFile, true);
File.Delete(s);
}
我建议在代码文件的顶部添加一个using System.IO;
,以避免在没有使用