|
|
@@ -1,11 +1,47 @@
|
|
|
namespace MeloongCore;
|
|
|
-public static class PathUtils {
|
|
|
+public static class FileUtils {
|
|
|
+
|
|
|
+ #region 写入
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// 写入文件。
|
|
|
+ /// 如果文件或文件夹不存在,则会自动创建。
|
|
|
+ /// </summary>
|
|
|
+ public static void Write(string filePath, string text, Encoding? encoding = null) {
|
|
|
+ DirectoryUtils.Create(filePath, isFilePath: true);
|
|
|
+ File.WriteAllText(filePath, text, encoding ?? new UTF8Encoding());
|
|
|
+ }
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// 写入文件。
|
|
|
+ /// 如果文件或文件夹不存在,则会自动创建。
|
|
|
+ /// </summary>
|
|
|
+ public static void Write(string filePath, byte[] content) {
|
|
|
+ DirectoryUtils.Create(filePath, isFilePath: true);
|
|
|
+ File.WriteAllBytes(filePath, content);
|
|
|
+ }
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// 将 <paramref name="stream" /> 写入文件。
|
|
|
+ /// 会将流的位置主动重置到开头。
|
|
|
+ /// 如果文件或文件夹不存在,则会自动创建。
|
|
|
+ /// </summary>
|
|
|
+ public static void Write(string filePath, Stream stream) {
|
|
|
+ DirectoryUtils.Create(filePath, isFilePath: true);
|
|
|
+ using FileStream fileStream = new(filePath, FileMode.Create, FileAccess.Write);
|
|
|
+ if (stream.CanSeek && stream.Position != 0) stream.Seek(0, SeekOrigin.Begin);
|
|
|
+ stream.CopyTo(fileStream);
|
|
|
+ }
|
|
|
+
|
|
|
+ #endregion
|
|
|
+
|
|
|
+ #region 短路径
|
|
|
|
|
|
/// <summary>
|
|
|
/// 若路径较长,则尽量将其转换为短路径。
|
|
|
/// 若输入的是文件夹路径,不保证其结尾是否有 \ 。
|
|
|
/// </summary>
|
|
|
- public static string Shorten(string fullName, bool keepFileName = false) {
|
|
|
+ public static string ShortenPath(string fullName, bool keepFileName = false) {
|
|
|
if (string.IsNullOrEmpty(fullName) || fullName.Length <= 200) return fullName;
|
|
|
fullName = fullName.Replace('/', '\\');
|
|
|
|
|
|
@@ -35,4 +71,6 @@ public static class PathUtils {
|
|
|
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
|
|
private static extern int GetShortPathNameW(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);
|
|
|
|
|
|
+ #endregion
|
|
|
+
|
|
|
}
|