Files
AohDrllTools/CommandTypeFileReader.cs

93 lines
3.1 KiB
C#

using System;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace DrillTools
{
internal static class CommandTypeFileReader
{
private const int Gb2312CodePage = 936;
private static readonly char[] ForbiddenPathChars =
{
'&', '|', '<', '>', '^', '%', '!', '(', ')', '@', '"', '\r', '\n'
};
public static string ReadAllText(string filePath)
{
return ReadAllText(filePath, CreateAnsiEncoding());
}
public static string ReadAllText(string filePath, Encoding encoding)
{
string normalizedPath = ValidateAndNormalizePath(filePath);
using var process = new Process
{
StartInfo = CreateStartInfo(normalizedPath, encoding)
};
if (!process.Start())
throw new InvalidOperationException("无法启动文件读取进程");
var outputTask = process.StandardOutput.ReadToEndAsync();
var errorTask = process.StandardError.ReadToEndAsync();
process.WaitForExit();
string output = outputTask.GetAwaiter().GetResult();
string error = errorTask.GetAwaiter().GetResult();
if (process.ExitCode != 0)
throw new InvalidOperationException($"读取文件失败,退出代码:{process.ExitCode},错误:{error.Trim()}");
return output;
}
private static ProcessStartInfo CreateStartInfo(string filePath, Encoding encoding)
{
return new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/d /c type \"{filePath}\"",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
StandardOutputEncoding = encoding,
StandardErrorEncoding = encoding
};
}
private static string ValidateAndNormalizePath(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
throw new ArgumentException("文件路径不能为空", nameof(filePath));
if (filePath.IndexOfAny(ForbiddenPathChars) >= 0)
throw new ArgumentException("文件路径包含不允许的命令行特殊字符", nameof(filePath));
string normalizedPath = Path.GetFullPath(filePath);
if (normalizedPath.IndexOfAny(ForbiddenPathChars) >= 0)
throw new ArgumentException("文件路径包含不允许的命令行特殊字符", nameof(filePath));
if (!File.Exists(normalizedPath))
throw new FileNotFoundException($"文件不存在:{normalizedPath}", normalizedPath);
return normalizedPath;
}
private static Encoding CreateAnsiEncoding()
{
try
{
return Encoding.GetEncoding(Gb2312CodePage);
}
catch
{
return Encoding.Default;
}
}
}
}