C#中文件夹类Directory的常用操作
.Directory方便我们对文件操作,首先引用命名空间 using System.IO;
- Directory.CreateDirectory():用于创建文件,传入路径即可
Directory.CreateDirectory(@"D:\test");
- Directory.Delete(): 用于删除文件,传入路径即可
Directory.Delete(@"D:\test",true);
3.Directory.Exists():判断文件是否存在 ,可搭配创建文件一起使用
if (Directory.Exists(@"D:\test")) {Directory.CreateDirectory(@"D:\test);}
4.Directory.GetFiles():获取所有的文件
string[] files = Directory.GetFiles(path);
5.Directory.GetDirectories(); 获取所有的文件夹;
string[] directories = Directory.GetDirectories(path);
获取 streamingAssets下所有的文件夹及文件生成树结构物体 ,代码如下
public class CubeGenerator : MonoBehaviour
{public GameObject folderPrefab; // 文件夹的Prefabpublic GameObject filePrefab; // 文件的Prefabvoid Start(){string streamingAssetsPath = Application.streamingAssetsPath;GenerateObjectTree(streamingAssetsPath, null);}void GenerateObjectTree(string path, Transform parent){// 创建文件夹物体GameObject folderObject = Instantiate(folderPrefab, Vector3.zero, Quaternion.identity, parent);folderObject.name = Path.GetFileName(path);// 获取文件夹下的所有文件和文件夹string[] files = Directory.GetFiles(path);string[] directories = Directory.GetDirectories(path);// 递归处理文件夹foreach (string directory in directories){GenerateObjectTree(directory, folderObject.transform);}// 创建文件物体foreach (string file in files){if (file.EndsWith(".meta")){continue;}GameObject fileObject = Instantiate(filePrefab, Vector3.zero, Quaternion.identity, folderObject.transform);fileObject.name = Path.GetFileName(file);}}
}