C# Directory用法之创建删除移动文件夹,获取子目录、文件名等
Directory Class,命名空间:System.IO
Path Class是用于通过目录和子目录进行创建、移动和枚举的静态方法。
static void Main(string[] args)
{
//获取应用程序当前工作路径
//返回String类型
string appPath = Directory.GetCurrentDirectory();
Console.WriteLine("当前应用程序的路径为:" + appPath);
//创建目录
//指定路径中创建所有目录和子目录,当LSTOther存在了,那就创建Test再在Test子文件夹下创建Other
//无论指定路径的目录是否已经存在,都返回DirectoryInfo的对象
DirectoryInfo a = Directory.CreateDirectory(appPath);
Directory.CreateDirectory(appPath + "\\Delete1");//在Other里创建一个Delete1的子文件夹
Directory.CreateDirectory(appPath + "\\Delete2");//在Other里创建一个Delete2的子文件夹
Directory.CreateDirectory(appPath + "\\Delete2\\1");//在Delete2里创建一个1的子文件夹
Directory.CreateDirectory(appPath + "\\Delete2\\2");//在Delete2里创建一个2的子文件夹
Directory.CreateDirectory(appPath + "\\Delete2\\3");//在Delete2里创建一个3的子文件夹
//获取当前目录的子目录(包括其路径)
//返回String数组类型
string[] pathArr = Directory.GetDirectories(appPath);
Console.WriteLine("该目录的子目录如下:");
for (int i = 0; i < pathArr.Length; i++)
Console.WriteLine(pathArr[i]);
//返回指定目录中与指定的搜索模式匹配的子目录的名称(包括其路径)
//第二个参数可以包含有效文本和通配符的组合,但不支持正则表达式。
//返回String数组类型
string[] pathArr2 = Directory.GetDirectories(appPath, "*1");
Console.WriteLine("该目录的子目录中含有1的子目录如下:");
for (int i = 0; i < pathArr2.Length; i++)
Console.WriteLine(pathArr2[i]);
//获取当前目录的所有文件(包括其路径)
//返回String数组类型
string[] filesPathArr = Directory.GetFiles(appPath);
Console.WriteLine("该目录的所有文件如下:");
for (int i = 0; i < filesPathArr.Length; i++)
Console.WriteLine(filesPathArr[i]);
//返回指定目录中与指定的搜索模式匹配的文件的名称(包括其路径)
//第二个参数可以包含有效文本和通配符的组合,但不支持正则表达式。
//返回String数组类型
string[] filesPathArr2 = Directory.GetFiles(appPath, "*.exe");
Console.WriteLine("该目录的所有文件中含有1的子目录如下:");
for (int i = 0; i < filesPathArr2.Length; i++)
Console.WriteLine(filesPathArr2[i]);
//获取目录的创建日期和时间
//返回DateTime类型
DateTime time = Directory.GetCreationTime(appPath + "\\Delete1");
Console.WriteLine("目录Delete1创建的时间为:" + time.ToString());
//获取目录的创建日期和时间,时间格式为UTC 时间
//返回DateTime类型
DateTime timeUTC = Directory.GetCreationTime(appPath + "\\Delete1");
Console.WriteLine("目录Delete1创建的时间为(UTC格式的):" + timeUTC.ToString());
//删除指定的空目录
//删除Other文件夹,Other文件夹必须是空目录,否则会报异常
Directory.Delete(appPath + "\\Delete1");
//删除指定的目录下及目录下的子目录和文件
//删除Other文件夹和Other文件夹下的子文件夹和文件
Directory.Delete(appPath + "\\Delete2", true);
//判断该路径目录是否存在,存在返回true,不存在返回false
//删除Other文件夹和Other文件夹下的子文件夹和文件
if (Directory.Exists(appPath))
Console.WriteLine("目录:" + appPath + " 存在");
else
Console.WriteLine("目录:" + appPath + " 不存在");
//将文件或目录及其内容移到新位置
Directory.Move(appPath + "\\Test\\a.jpg", appPath + "\\newTest\\a.jpg");
}
运行后的效果: