在 C# 中创建文件夹和文件,主要是借助 .NET 框架提供的相关类和方法与操作系统进行交互,以下详细介绍创建文件夹和文件的原理及实现方式。
创建文件夹的原理
- 涉及的类和方法
在 C# 里,创建文件夹主要使用 System.IO 命名空间下的 Directory 类或 DirectoryInfo 类。
Directory 类:这是一个静态类,提供了一系列用于操作目录的静态方法,这些方法直接对文件系统进行操作,无需创建对象实例即可调用。
DirectoryInfo 类:它是一个实例类,代表文件系统中的一个目录,通过创建 DirectoryInfo 对象来操作特定的目录。 - 实现原理
当调用创建文件夹的方法时,程序会向操作系统发送请求,要求在指定的路径下创建一个新的文件夹。操作系统会检查该路径是否合法,以及是否有足够的权限进行创建操作。如果路径合法且权限足够,操作系统会在文件系统中创建相应的文件夹。
实现代码如下:
using System;
using System.IO;
class Program
{
static void Main()
{
// 使用 Directory 类创建文件夹
string directoryPath = @"C:\TestFolder";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
Console.WriteLine("使用 Directory 类创建文件夹成功");
}
// 使用 DirectoryInfo 类创建文件夹
DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\TestFolder2");
if (!directoryInfo.Exists)
{
directoryInfo.Create();
Console.WriteLine("使用 DirectoryInfo 类创建文件夹成功");
}
}
}
判断文件夹存不存在,不存在就创建
在加一个遍历文件夹的操作
代码如下:
if (Directory.Exists(fullPath))
{ //按钮
DirectoryInfo direction = new DirectoryInfo(fullPath);
FileInfo[] files = direction.GetFiles("*.xml", SearchOption.AllDirectories);
//图片
DirectoryInfo photo = new DirectoryInfo(fullPathPhoto);
FileInfo[] fileoto = photo.GetFiles("*.png", SearchOption.AllDirectories);
// Debug.Log(files.Length);
for (int i = 0; i < files.Length; i++)
{
if (files[i].Name.EndsWith(".meta"))
{
continue;
}
//if (fileoto[i].Name.EndsWith(".meta")) {
// continue;
//}
string str = files[i].Name;
string clone = ".xml";
Regex r = new Regex(clone);
Match m = r.Match(str);
//图片
string oto = fileoto[i].Name;
string clo = ".png";
Regex ro = new Regex(clo);
Match mo = ro.Match(oto);
if (m.Success && mo.Success)
{
str = str.Replace(clone, "");
oto = oto.Replace(clo, "");
}
}
}