目录
本篇文章分享一下Directory类和File类。在C#和Unity开发中,System.IO.Directory和System.IO.File是处理文件系统的核心类,分别用于操作目录(文件夹)和文件。它们提供了简洁的静态方法,无需需实例化即可直接使用,是实现文件管理、数据持久化等功能的基础工具。
Directory类和File类
1.Directory类:管理目录(文件夹)
Directory 类提供静态方法,用于创建、删除、查询目录等操作,无需实例化即可使用,适用于管理文件的存储结构(如游戏存档文件夹、日志目录等)。
核心功能与常用方法
| 方法签名 | 功能描述 | Unity 场景示例 |
| Directory.CreateDirectory(string path) | 创建指定路径的目录(若父目录不存在则递归创建) | 创建游戏存档目录:Directory. CreateDirectory(Application. persistentDataPath + "/Saves") |
| Directory.Delete(string path, bool recursive) | 删除目录。recursive:为true 表示强制删除(包括子目录和文件) | 清理临时缓存:Directory.Delete (Application.temporaryCachePath, true) |
| Directory.Exists(string path) | 检查目录是否存在 | 存档前检查目录是否存在:if (!Directory.Exists(saveDir)) { ... } |
| Directory.GetDirectories(string path) | 获取指定目录下的所有子目录路径 | 遍历用户创建的存档文件夹:string[] saveFolders = Directory.GetDirectories(saveRoot) |
| Directory.GetFiles(string path, string searchPattern) | 获取目录中符合条件的文件路径(searchPattern支持通配符 * ?) | 查找所有.json 存档文件:Directory.GetFiles(saveDir, "*.json") |
| Directory.Move(string sourceDirName, string destDirName) | 移动或重命名目录(若目标存在则报错) | 重命名存档文件夹:Directory.Move(oldPath, newPath) |
| Directory.GetCreationTime(string path) | 获取目录的创建时间 | 按创建时间排序存档:var createTime = Directory.GetCreationTime(folderPath) |
2.File类:管理文件
File 类同样提供静态方法,用于文件的创建、读写、复制等操作,是处理具体数据的主要工具(如文本、二进制文件)。
核心功能与常用方法
| 方法签名 | 功能描述 | Unity 场景示例 |
| File.WriteAllText(string path, string contents) | 写入文本(覆盖现有内容) | 保存 JSON 存档:File.WriteAllText(savePath, jsonData) |
| File.AppendAllText(string path, string contents) | 追加文本到文件末尾 | 记录运行日志:File.AppendAllText(logPath, "错误信息:xxx\n") |
| File.ReadAllText(string path) | 读取文件的所有文本内容 | 加载 JSON 存档:string json = File.ReadAllText(loadPath) |
| File.WriteAllBytes(string path, byte[] bytes) | 写入二进制数据到文件 | 保存截图(PNG 格式):File.WriteAllBytes(screenshotPath, texture.EncodeToPNG()) |
| File.ReadAllBytes(string path) | 读取文件的所有二进制数据 | 加载自定义二进制资源:byte[] data = File.ReadAllBytes(resourcePath) |
| File.Copy(string sourceFileName, string destFileName, bool overwrite) | 复制文件,overwrite: true 表示覆盖目标文件 | 备份存档:File.Copy(savePath, backupPath, true) |
| File.Move(string sourceFileName, string destFileName) | 移动或重命名文件(若目标存在则报错) | 转移过期日志到归档目录:File.Move(logPath, archivePath) |
| File.Delete(string path) | 删除指定文件 | 删除旧存档:File.Delete(oldSavePath) |
| File.Exists(string path) | 检查文件是否存在 | 加载前检查存档是否存在:if (File.Exists(loadPath)) { ... } |
| File.GetLastWriteTime(string path) | 获取文件最后修改时间 | 显示存档更新时间:var time = File.GetLastWriteTime(savePath) |
3.在Unity中使用的注意事项
3.1.路径选择
(1)优先使用Unity提供的跨平台路径:想要进一步了解可以查看Unity的常用路径和特殊文件夹
Application.persistentDataPath:可读写的持久化目录(推荐用于存档、配置)。
Application.streamingAssetsPath:只读资源目录(打包后无法修改,适合存放初始配置)。
(2)避免硬编码绝对路径(如C:/Files),使用Path.Combine拼接路径(自动适配系统分隔符)
string path = Path.Combine(Application.persistentDataPath, "Data", "save.json");
3.2.平台限制
(1)WebGL:无法直接使用File/Directory操作本地文件,需通过UnityWebRequest读取streamingAssetsPath资源。
(2)移动端(Android/iOS):受沙盒限制,仅能访问应用私有目录(如persistentDataPath),无法直接操作系统目录(如相册需通过原生API)。
3.3.性能与线程
(1)大文件(如>100MB)建议用FileStream分块读写,并在子线程执行,避免阻塞Unity主线程。
(2)频繁写入(如日志)可先缓存到内存,定时批量写入磁盘,减少IO开销。
4.示例
using System.IO;
using UnityEngine;
public class FileTest : MonoBehaviour
{
private void Start()
{
//1.创建存档目录
string saveDir = Path.Combine(Application.persistentDataPath, "PlayerSaves");
if (!Directory.Exists(saveDir))
{
Directory.CreateDirectory(saveDir);//自动创建多级目录
}
//2.写入存档文件
string savePath = Path.Combine(saveDir, "player1.json");
string playerData = JsonUtility.ToJson(new Player { level = 10, name = "Test" });
File.WriteAllText(savePath, playerData);
//3.复制备份
string backupPath = Path.Combine(saveDir, "player1_backup.json");
File.Copy(savePath, backupPath, overwrite: true);
//4.读取所有存档
foreach (string file in Directory.GetFiles(saveDir, "*.json"))
{
string data = File.ReadAllText(file);
Debug.Log("加载存档:" + data);
}
//5.删除过期存档
//if (File.Exists(oldSavePath))
//{
// File.Delete(oldSavePath);
//}
}
}
public class Player
{
public string name;
public int level;
}
5.总结
Directory和File类是C#与Unity中文件系统操作的基础,通过它们可以实现目录管理、文件读写、数据备份等核心功能。在Unity中使用时,需注意跨平台路径兼容和平台限制,结合using语句(如操作FileStream时)确保资源释放,以实现高效、稳定的文件操作。想要了解using的使用可查看【超详细】using语句
好了,本次的分享到这里就结束啦,希望对你有所帮助~

150

被折叠的 条评论
为什么被折叠?



