首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> C# 入門

C# 擴展方法讓 string 翻身:文件操作、網址開啟、DOS 命令一把罩

     編輯:C# 入門

前言

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) 更符合物件導向思維。

三、執行 DOS 命令

// 簡單範例
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 將導致命令注入漏洞。實務上必須:

  • 嚴格驗證/白名單過濾輸入字串
  • 避免在 Web 應用中暴露此功能
  • 考慮使用 ProcessStartInfo 參數化傳遞引數,而非字串拼接

延伸想法

同理可擴展:string.ToMd5()、string.EncryptAes(key)、string.SendEmail() 等。但需遵循「單一職責」,避免讓 string 變成「神物件」。建議將領域相關擴展放入專屬命名空間 (如 MyApp.Extensions.IO),按需 using。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved