BITKit/Src/Core/Utils/PathHelper.cs

77 lines
2.4 KiB
C#
Raw Normal View History

2023-06-05 19:57:17 +08:00
using System;
using System.IO;
2023-06-29 14:57:11 +08:00
2023-06-05 19:57:17 +08:00
namespace BITKit
{
public class PathHelper
{
2023-06-29 14:57:11 +08:00
private static string appDataPath = _appDataPath;
2023-06-05 19:57:17 +08:00
[ExcuteOnAwake]
public static void Init()
{
if (string.IsNullOrEmpty(appDataPath))
{
appDataPath = Path.Combine(Environment.CurrentDirectory, BITApp.AppName);
}
2023-06-29 14:57:11 +08:00
2023-06-05 19:57:17 +08:00
BIT4Log.Log<PathHelper>($"配置文件路径:{appDataPath}");
DirectoryInfo directoryInfo = new(appDataPath);
directoryInfo.Create();
}
2023-06-29 14:57:11 +08:00
2023-06-05 19:57:17 +08:00
public static string GetFolderPath(params string[] paths)
{
var path = GetPath(paths);
if (path is not null)
{
DirectoryInfo directoryInfo = new(path);
directoryInfo.Create();
Directory.CreateDirectory(path);
return path;
}
2023-06-29 14:57:11 +08:00
2023-06-05 19:57:17 +08:00
return GetPath(paths);
}
2023-10-06 23:43:19 +08:00
public static void EnsureDirectoryCreated(string path)
{
path = Path.GetDirectoryName(path);
2024-03-31 23:31:00 +08:00
if (Directory.Exists(path)) return;
2023-10-06 23:43:19 +08:00
if (path != null) Directory.CreateDirectory(path);
}
2023-06-29 14:57:11 +08:00
2023-06-05 19:57:17 +08:00
public static string GetFilePath(params string[] paths)
{
var path = GetPath(paths);
var dictionaryPath = Path.GetDirectoryName(path);
Directory.CreateDirectory(dictionaryPath);
2024-03-31 23:31:00 +08:00
if (File.Exists(path)) return path;
using var fs = File.Create(path);
fs.Close();
fs.Dispose();
2023-06-29 14:57:11 +08:00
2023-06-05 19:57:17 +08:00
return path;
}
2023-06-29 14:57:11 +08:00
2023-06-05 19:57:17 +08:00
public static string GetTempFilePath(string fileName = null)
{
2024-03-31 23:31:00 +08:00
var path = GetFilePath("Temps", fileName ?? Guid.NewGuid().ToString());
2023-06-05 19:57:17 +08:00
return path;
}
2023-06-29 14:57:11 +08:00
2023-06-05 19:57:17 +08:00
public static string GetPath(params string[] paths)
{
return Path.Combine(appDataPath, Path.Combine(paths));
}
2023-06-29 14:57:11 +08:00
public static bool TryGetText(string path, out string text)
{
path = Path.Combine(appDataPath, path);
text = string.Empty;
if (!File.Exists(path)) return false;
text = File.ReadAllText(path);
return true;
}
private static string _appDataPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
2023-06-05 19:57:17 +08:00
BITApp.AppName);
}
}