76 lines
2.1 KiB
C#
76 lines
2.1 KiB
C#
using System.ComponentModel;
|
|
using System.Text;
|
|
|
|
namespace MAF1.Tools;
|
|
|
|
public static class FileTools
|
|
{
|
|
[Description("Read the full UTF-8 text of a local file. Always call this before judging city names.")]
|
|
public static string ReadTextFile([Description("Absolute or relative path of the file to read.")] string path)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(path))
|
|
{
|
|
return "未提供文件路径。";
|
|
}
|
|
|
|
string? resolved = Resolve(path.Trim().Trim('"'));
|
|
if (resolved is null)
|
|
{
|
|
return $"找不到文件:{path}";
|
|
}
|
|
|
|
FileInfo info = new(resolved);
|
|
if (info.Length > 64 * 1024)
|
|
{
|
|
return $"文件过大({info.Length} 字节),请换一个不超过 64KB 的文本文件。";
|
|
}
|
|
|
|
return File.ReadAllText(resolved, Encoding.UTF8);
|
|
}
|
|
|
|
private static string? Resolve(string path)
|
|
{
|
|
if (Path.IsPathRooted(path) && File.Exists(path))
|
|
{
|
|
return Path.GetFullPath(path);
|
|
}
|
|
|
|
string fromCwd = Path.GetFullPath(path);
|
|
if (File.Exists(fromCwd))
|
|
{
|
|
return fromCwd;
|
|
}
|
|
|
|
foreach (string root in SearchRoots())
|
|
{
|
|
string candidate = Path.GetFullPath(Path.Combine(root, path));
|
|
if (File.Exists(candidate))
|
|
{
|
|
return candidate;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private static IEnumerable<string> SearchRoots()
|
|
{
|
|
yield return AppContext.BaseDirectory;
|
|
string? contentRoot = Environment.GetEnvironmentVariable("MAF1_CONTENT_ROOT");
|
|
if (!string.IsNullOrWhiteSpace(contentRoot))
|
|
{
|
|
yield return contentRoot;
|
|
}
|
|
|
|
DirectoryInfo? parent = Directory.GetParent(AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar));
|
|
if (parent is not null)
|
|
{
|
|
yield return parent.FullName;
|
|
if (parent.Parent is not null)
|
|
{
|
|
yield return parent.Parent.FullName;
|
|
}
|
|
}
|
|
}
|
|
}
|