Skip to content

Commit 7f33d68

Browse files
committed
💾 Feat: 增加把字符串作为文件路径读取内容的扩展方法, 同时支持同步和异步, 异步仅在 .net standard 2.1 及以上可用
1 parent a8e6464 commit 7f33d68

1 file changed

Lines changed: 31 additions & 1 deletion

File tree

Common.BasicHelper/Util/Extension/StringHelper.cs

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
using System.Text;
1+
using System.IO;
2+
using System.Text;
3+
using System.Threading.Tasks;
24

35
namespace Common.BasicHelper.Util.Extension;
46

@@ -25,4 +27,32 @@ public static string Num2UpperChar(this string source)
2527
return sb.ToString();
2628
}
2729

30+
/// <summary>
31+
/// 从磁盘读取全部文本
32+
/// </summary>
33+
/// <param name="path">文件路径</param>
34+
/// <returns>文本内容, 若文件不存在则返回空</returns>
35+
public static string ReadAllTextFromDisk(this string path)
36+
{
37+
if (File.Exists(path))
38+
return File.ReadAllText(path);
39+
else return null;
40+
}
41+
42+
#if NETSTANDARD2_1_OR_GREATER
43+
44+
/// <summary>
45+
/// 从磁盘异步读取全部文本
46+
/// </summary>
47+
/// <param name="path">文件路径</param>
48+
/// <returns>文本内容读取任务, 若文件不存在则返回空</returns>
49+
public static Task<string> ReadAllTextFromDiskAsync(this string path)
50+
{
51+
if (File.Exists(path))
52+
return File.ReadAllTextAsync(path);
53+
else return null;
54+
}
55+
56+
#endif
57+
2858
}

0 commit comments

Comments
 (0)