using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using ScrewsMaster; using UnityEngine; using UnityEngine.AddressableAssets; using UnityEngine.Networking; using UnityEngine.ResourceManagement.AsyncOperations; namespace Roy { public class FileNetworkManager : BaseManager { private readonly string _copyFolderPath; private readonly string _configFolderPath; public const string FolderName = "Configs"; public const string FolderLabel = "config"; public FileNetworkManager() { _copyFolderPath = Path.Combine(Application.streamingAssetsPath, FolderName); _configFolderPath = Path.Combine(Application.persistentDataPath, FolderName); } public string GetConfigFOlderPath() { return _configFolderPath; } // 示例解析文件列表方法(你可以根据实际需求实现) List ParseFileList(string data) { // 假设 data 是文件列表的文本,解析文件名 // 根据实际情况解析,例如通过换行符分割 return data.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).ToList(); } public void CopyStreamingAssetsToPersistentDataPath(Action onComplete = null) { // 如果目标文件夹不存在,创建它 if (!Directory.Exists(_configFolderPath)) { Directory.CreateDirectory(_configFolderPath); } CrazyAsyKit.StartCoroutine(CopyFile(onComplete)); // // 获取StreamingAssets中的文件,排除后缀为.meta的文件 // var files = Directory.GetFiles(_copyFolderPath) // .Where(file => !file.EndsWith(".meta")) // 过滤 .meta 文件 // .ToList(); // 转换为列表以方便使用 // // if (files.Count == 0) // { // onComplete?.Invoke(true); // 如果没有文件,直接回调成功 // return; // } // // // 使用计数器来跟踪完成的文件复制 // int completedCount = 0; // // foreach (var file in files) // { // string fileName = Path.GetFileName(file); // string sourceFilePath = file; // 原始文件路径 // string destFilePath = Path.Combine(_configFolderPath, fileName); // // // 读取并写入文件 // CrazyAsyKit.StartCoroutine(CopyFile(sourceFilePath, destFilePath, // (result) => // { // completedCount++; // // 如果所有文件都已复制完成,调用回调 // if (completedCount == files.Count) // { // onComplete?.Invoke(true); // } // })); // } } private IEnumerator CopyFile(Action onComplete = null) { var handle = Addressables.LoadResourceLocationsAsync(FolderLabel); yield return handle; if (handle.Status == AsyncOperationStatus.Succeeded) { // 查找以 ".json" 结尾的文件 var jsonLocation = handle.Result.FirstOrDefault(loc => loc.PrimaryKey.EndsWith(".json")); if (jsonLocation != null) { var jsonFileName = Path.GetFileName(jsonLocation.PrimaryKey); // 加载 JSON 文件 var textAssetAsync = Addressables.LoadAssetAsync(jsonLocation); yield return textAssetAsync; if (textAssetAsync.Status == AsyncOperationStatus.Succeeded) { TextAsset jsonFile = textAssetAsync.Result; Debug.Log("Loaded JSON content: " + jsonFile.text); string destFilePath = Path.Combine(_configFolderPath, jsonFileName); File.WriteAllBytes(destFilePath, jsonFile.bytes); onComplete?.Invoke(true); } else { Debug.LogError("Failed to load JSON file"); onComplete?.Invoke(false); } } else { Debug.LogError("No JSON file found in folder"); onComplete?.Invoke(false); } } else { Debug.LogError("Failed to load folder resources"); onComplete?.Invoke(false); } } private IEnumerator CopyFile(string sourceFile, string destFile, Action onComplete = null) { string filePath = "file://" + sourceFile; using (UnityWebRequest www = UnityWebRequest.Get(filePath)) { yield return www.SendWebRequest(); if (www.result == UnityWebRequest.Result.Success) { File.WriteAllBytes(destFile, www.downloadHandler.data); Debug.Log($"File copied to {destFile}"); onComplete?.Invoke(true); } else { Debug.LogError("Failed to copy file: " + www.error); onComplete?.Invoke(false); } } } /// /// 读取或下载 /// /// /// public void ReadData(string path, Action callback) { CrazyAsyKit.StartCoroutine(ReadDataEnumerator(path, callback)); } /// /// 读取或下载 /// /// /// /// private IEnumerator ReadDataEnumerator(string path, Action callback) { string fullPath; // 判断是网络URL还是本地文件路径 if (path.StartsWith("http://") || path.StartsWith("https://")) { fullPath = path; // 网络URL } else { // 本地文件路径 fullPath = "file://" + path; } // 使用UnityWebRequest读取数据 using (UnityWebRequest webRequest = UnityWebRequest.Get(fullPath)) { yield return webRequest.SendWebRequest(); if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError) { Debug.LogError($"Error while reading file: {webRequest.error} path: {fullPath}"); callback?.Invoke(null); // 返回null表示出错 } else { string data = webRequest.downloadHandler.text; Debug.Log($"Data read successfully: {data}"); callback?.Invoke(data); // 通过回调传出数据 } } } /// /// 将内容写入指定文件,并删除原有文件。 /// /// 文件夹名称 /// 文件名称 /// 要写入的内容 public void WriteToPersistentData(string folderName, string fileName, string content) { // 获取持久化数据路径 string folderPath = Path.Combine(Application.persistentDataPath, folderName); // 如果文件夹不存在,则创建它 if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } // 删除原有文件 var existingFiles = Directory.GetFiles(folderPath); foreach (var file in existingFiles) { File.Delete(file); } // 完整文件路径 string filePath = Path.Combine(folderPath, fileName); // 写入新文件 File.WriteAllText(filePath, content); Debug.Log($"File written to: {filePath}"); } /// /// 提取指定目录下所有文件文件名 /// /// /// public string[] GetFileNamesFromPersistentDataPath(string subdirectory) { string directoryPath = Path.Combine(Application.persistentDataPath, subdirectory); if (Directory.Exists(directoryPath)) { // 获取目录中的所有文件名 return Directory.GetFiles(directoryPath) .Select(Path.GetFileName) // 只提取文件名 .ToArray(); } else { Debug.LogWarning($"Directory does not exist: {directoryPath}"); return new string[0]; // 返回空数组 } } } }