User Tools

Site Tools


blog:2025-06-20-001



2025-06-20 以C# Replace 一個C# file中所定義的特定 class 以內的 code

  • C# 要產生一個新 function ,如Replace 一個C# file中 所定義的特定 class 以內的 code 要replace 成新產生的
  • 要在 C# 中產生一個新的函數,來替換指定 class 內的特定程式碼,使用以下的步驟和範例程式碼
  • 這個範例將會讀取一個 C# 檔案,尋找特定的 class 並替換其內部的程式碼

步驟

  • 讀取檔案:從指定的 C# 檔案中讀取內容。
  • 尋找並替換:使用正則表達式或字串操作來尋找特定的 class 並替換其內容。
  • 寫入檔案:將修改後的內容寫回到檔案中。

範例程式碼

  • 以下是一個簡單的 C# 程式,實現了上述功能:
    using System;
    using System.IO;
    using System.Text.RegularExpressions;
    
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "YourFilePath.cs"; // 替換為你的檔案路徑
            string className = "Json1";
            string newCode = @"
            public uint gData1 { get; set; } // [1] gData1 
            public Int16 gData2 { get; set; } // [2] gData2 
            public Int16 gData3 { get; set; } // [4] gData3 
            public Int16 gData4 { get; set; } // [5] gData4 
            public Int32 gData5 { get; set; } // [6] gData5 
            ";
    
            ReplaceClassCode(filePath, className, newCode);
        }
    
        static void ReplaceClassCode(string filePath, string className, string newCode)
        {
            // 讀取檔案內容
            string fileContent = File.ReadAllText(filePath);
    
            // 使用正則表達式尋找 class 並替換其內容
            string pattern = $@"(public class {className}\s*{{\s*).*?(}})";
            string replacement = $"$1{newCode}$2";
            string updatedContent = Regex.Replace(fileContent, pattern, replacement, RegexOptions.Singleline);
    
            // 寫回檔案
            File.WriteAllText(filePath, updatedContent);
            Console.WriteLine($"Class {className} has been updated successfully.");
        }
    }

說明

  • 正則表達式:
    • 這段程式碼使用正則表達式來匹配 Json1 類別的內容
    • (public class {className}\s*{{\s*).*?(}}) 這個模式
  • 匹配類別的開頭和結尾,並捕獲中間的內容
  • 替換內容:將新的程式碼插入到匹配的內容中
  • 寫入檔案:將更新後的內容寫回到原始檔案中
  • 注意事項
    • 確保在執行此程式之前備份原始檔案,以防止意外損壞
    • 根據需要調整檔案路徑和新的 class 內容

TAGS

  • 6 person(s) visited this page until now.

blog/2025-06-20-001.txt · Last modified: 2025/06/20 10:01 by jethro