.Directory方便我们对文件操作,首先引用命名空间 using System.IO;
Directory.CreateDirectory(@"D:\test");
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; // 文件夹的Prefab
public GameObject filePrefab; // 文件的Prefab
void 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);
}
}
}