2026-06-15 13:18:37 +03:00

107 lines
3.2 KiB
C#

using System;
using System.IO;
using UnityEngine;
public class FileUtil
{
public static (bool OK, string Message) SaveText(string fileName, string filePath, string content)
{
try
{
string fullPath = Path.Combine(filePath, fileName);
string directory = Path.GetDirectoryName(fullPath);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
File.WriteAllText(fullPath, content);
return (true, $"Файл успешно сохранен: {fullPath}");
}
catch (Exception ex)
{
return (false, $"Ошибка сохранения: {ex.Message}");
}
}
public static (bool OK, string Message, string Content) LoadText(string fileName, string filePath)
{
try
{
string fullPath = Path.Combine(filePath, fileName);
if (!File.Exists(fullPath))
{
return (false, $"Файл не найден: {fullPath}", null);
}
string content = File.ReadAllText(fullPath);
return (true, $"Файл успешно загружен: {fullPath}", content);
}
catch (Exception ex)
{
return (false, $"Ошибка загрузки: {ex.Message}", null);
}
}
public static (bool OK, string Message) SaveJson<T>(string fileName, string filePath, T data)
{
try
{
string json = JsonUtility.ToJson(data, true);
return SaveText(fileName, filePath, json);
}
catch (Exception ex)
{
return (false, $"Ошибка сохранения JSON: {ex.Message}");
}
}
public static (bool OK, string Message) SaveJson<T>(string fileName, AppDirectory directory, T data)
=> SaveJson<T>(fileName, GetDirectoryName(directory), data);
private static string GetDirectoryName(AppDirectory directory)
{
return directory switch
{
AppDirectory.Streaming => Application.streamingAssetsPath,
AppDirectory.Persistent => Application.persistentDataPath,
_ => Path.Combine(Application.persistentDataPath, "TRASH")
};
}
public static (bool OK, string Message, T Data) LoadJson<T>(string fileName, string filePath) where T : new()
{
try
{
var result = LoadText(fileName, filePath);
if (!result.OK)
{
return (false, result.Message, default(T));
}
T data = JsonUtility.FromJson<T>(result.Content);
if (data == null)
{
return (false, "Ошибка десериализации JSON", default(T));
}
return (true, $"JSON успешно загружен: {fileName}", data);
}
catch (Exception ex)
{
return (false, $"Ошибка загрузки JSON: {ex.Message}", default(T));
}
}
public static (bool OK, string Message, T Data) LoadJson<T>(string fileName, AppDirectory directory) where T : new()
=> LoadJson<T>(fileName, GetDirectoryName(directory));
public enum AppDirectory
{
Streaming,
Persistent
}
}