string 作為最基礎的資料類型,長期只能被動接受 Substring、Split、Join 等操作。透過 C# 擴展方法,我們能賦予 string 豐富的行為能力,讓它「翻身做主」。本文展示三大類實用擴展:開啟文件/網址、文件目錄操作、執行 DOS 命令。
// 用法
@"c:\t.txt".Open();
@"https://www.cnblogs.com/ldp615/".Open();
// 實作
public static void Open(this string s)
{
System.Diagnostics.Process.Start(s);
}
利用 Process.Start 關聯系統預設程式開啟,支援本地檔案路徑與 URL。
// 用法
@"C:\Directory".CreateDirectory();
@"C:\Directory\Readme.txt".WriteText("this file is created by string!");
@"C:\abc.txt".DeleteFile();
// 實作
public static void CreateDirectory(this string path)
{
System.IO.Directory.CreateDirectory(path);
}
public static void WriteText(this string path, string contents)
{
System.IO.File.WriteAllText(path, contents);
}
public static void DeleteFile(this string path)
{
if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
}
封裝 System.IO 靜態方法,語意更直覺:path.CreateDirectory() 比 Directory.CreateDirectory(path) 更符合物件導向思維。
// 簡單範例
string output1 = @"del c:\t1.txt".RunCmd();
string output2 = @"dir c:\".RunCmd();
// 實作:捕獲標準輸出與錯誤輸出
public static string RunCmd(this string cmd)
{
using (var p = new System.Diagnostics.Process())
{
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c " + cmd;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
p.WaitForExit();
return output + error;
}
}
此擴展可同步執行命令並回傳輸出,適合自動化腳本、部署工具、系統管理程式。
⚠️ 極度危險:若字串來源不可信 (如使用者輸入),直接執行 RunCmd 將導致命令注入漏洞。實務上必須:
ProcessStartInfo 參數化傳遞引數,而非字串拼接同理可擴展:string.ToMd5()、string.EncryptAes(key)、string.SendEmail() 等。但需遵循「單一職責」,避免讓 string 變成「神物件」。建議將領域相關擴展放入專屬命名空間 (如 MyApp.Extensions.IO),按需 using。