109 lines
3.0 KiB
C#
109 lines
3.0 KiB
C#
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Text;
|
|
|
|
namespace ShrlAlgo.Toolkit.Core.Heplers;
|
|
|
|
public static class IOHelper
|
|
{
|
|
public static void GetFilesHierarchy(string path)
|
|
{
|
|
var files = Directory.GetFiles($"{path}", "*", SearchOption.AllDirectories); //遍历所有文件夹
|
|
var list = files.Union(files).OrderBy(s => s);
|
|
}
|
|
|
|
public static string GetRelativePath(string fromPath, string toPath)
|
|
{
|
|
Uri uri = new(fromPath);
|
|
Uri uri2 = new(toPath);
|
|
if (uri.Scheme != uri2.Scheme)
|
|
{
|
|
return toPath;
|
|
}
|
|
|
|
var uri3 = uri.MakeRelativeUri(uri2);
|
|
var text = Uri.UnescapeDataString(uri3.ToString());
|
|
if (uri2.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
|
|
{
|
|
text = text.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
|
|
}
|
|
|
|
return text;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取指定系统路径
|
|
/// </summary>
|
|
/// <param name="specialFolder"></param>
|
|
/// <returns></returns>
|
|
public static string GetSpecialFolderDir(Environment.SpecialFolder specialFolder)
|
|
{
|
|
return Environment.GetFolderPath(specialFolder);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 读文件
|
|
/// </summary>
|
|
/// <param name="path">文件路径</param>
|
|
/// <returns></returns>
|
|
public static string ReadFile(string path)
|
|
{
|
|
string s;
|
|
if (!File.Exists(path))
|
|
{
|
|
s = "不存在相应的目录";
|
|
}
|
|
else
|
|
{
|
|
using StreamReader f2 = new(path, Encoding.GetEncoding("gb2312"));
|
|
s = f2.ReadToEnd();
|
|
f2.Close();
|
|
}
|
|
|
|
return s;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 在桌面写文件
|
|
/// </summary>
|
|
/// <param name="fileName">纯文件名</param>
|
|
/// <param name="message">写入的内容</param>
|
|
public static void WriteTxtFile(string fileName, string message)
|
|
{
|
|
var filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + $"\\{fileName}.txt";
|
|
File.WriteAllText(filePath, message);
|
|
Process.Start(filePath);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 写文件
|
|
/// </summary>
|
|
/// <param name="path">文件路径</param>
|
|
/// <param name="strings">文件内容</param>
|
|
public static void WriteFile(string path, string strings)
|
|
{
|
|
if (!File.Exists(path))
|
|
{
|
|
var f = File.Create(path);
|
|
f.Close();
|
|
f.Dispose();
|
|
}
|
|
|
|
using StreamWriter f2 = new(path, true, Encoding.UTF8);
|
|
f2.WriteLine(strings);
|
|
f2.Close();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 向文本文件中写入内容
|
|
/// </summary>
|
|
/// <param name="filePath">文件的绝对路径</param>
|
|
/// <param name="text">写入的内容</param>
|
|
/// <param name="encoding">编码</param>
|
|
public static void WriteText(string filePath, string text, Encoding encoding)
|
|
{
|
|
//向文件写入内容
|
|
File.WriteAllText(filePath, text, encoding);
|
|
}
|
|
}
|