You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从读取为字符串的C#文件中提取变量并替换为MD5哈希值?

Got it, let's break this down into actionable steps to solve your problem—extracting variable names from a stringified C# file, storing them, then replacing each name with its MD5 hash. Here's a practical approach that balances simplicity and accuracy:

1. Extract Variable Names with Regex (Basic Approach)

For most common C# variable declarations, a carefully crafted regular expression can capture valid variable names. We need to match declarations that include:

  • Explicit types (e.g., int, string, List<int>)
  • Implicit var declarations
  • Multiple variables declared in one line (e.g., float x = 0.5f, y = 1.0f;)
  • Avoid matching keywords, method names, or class names

Here's a regex pattern that covers these cases:

var variableRegex = new Regex(
    @"(?:\b(?:var|int|string|bool|float|double|decimal|long|short|byte|char|object|List<[^>]+>|Dictionary<[^>]+,[^>]+>)\s+)(\w+)(?:\s*=\s*.+?)?(?:\s*,\s*(\w+)(?:\s*=\s*.+?)?)*",
    RegexOptions.Multiline | RegexOptions.IgnoreCase
);

To extract the names:

string codeAsString = File.ReadAllText("YourFile.cs"); // Or use your existing code string
List<string> variableNames = new List<string>();

foreach (Match match in variableRegex.Matches(codeAsString))
{
    // Add the first variable in the declaration line
    if (!string.IsNullOrEmpty(match.Groups[1].Value))
        variableNames.Add(match.Groups[1].Value);
    
    // Add any additional variables declared in the same line
    foreach (Capture capture in match.Groups[2].Captures)
    {
        if (!string.IsNullOrEmpty(capture.Value))
            variableNames.Add(capture.Value);
    }
}

// Remove duplicates to avoid redundant processing
variableNames = variableNames.Distinct().ToList();

Regex can fail with complex code (e.g., nested generics, anonymous types, properties). For production-grade accuracy, use the Roslyn .NET Compiler Platform to parse the code as syntax trees—it natively understands C# syntax, eliminating false matches.

First, add the NuGet package Microsoft.CodeAnalysis.CSharp to your project. Then:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

// Parse the code string into a syntax tree
SyntaxTree tree = CSharpSyntaxTree.ParseText(codeAsString);
CompilationUnitSyntax root = tree.GetCompilationUnitRoot();

// Traverse the tree to find all variable declarations
List<string> variableNames = new List<string>();
var variableDeclarators = root.DescendantNodes().OfType<VariableDeclaratorSyntax>();

foreach (var declarator in variableDeclarators)
{
    string varName = declarator.Identifier.Text;
    // Skip if it's a C# keyword (Roslyn usually filters these out, but extra safety never hurts)
    if (!SyntaxFacts.IsKeyword(varName))
        variableNames.Add(varName);
}

variableNames = variableNames.Distinct().ToList();
3. Replace Variable Names with MD5 Hash

Once you have your variable names, you need to replace each occurrence only when it's used as a variable (not in strings, comments, or method names). Use regex with word boundaries to avoid accidental replacements:

First, create a helper method to generate MD5 hashes:

private static string GetMd5Hash(string input)
{
    using (var md5 = System.Security.Cryptography.MD5.Create())
    {
        byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
        byte[] hashBytes = md5.ComputeHash(inputBytes);
        
        // Convert byte array to a lowercase hex string
        return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
    }
}

Then perform the replacement:

string modifiedCode = codeAsString;

foreach (var varName in variableNames)
{
    // Use word boundary regex to match only standalone variable names
    var replaceRegex = new Regex($@"\b{Regex.Escape(varName)}\b", RegexOptions.Multiline);
    string md5Hash = GetMd5Hash(varName);
    modifiedCode = replaceRegex.Replace(modifiedCode, md5Hash);
}

// Save or use the modified code
File.WriteAllText("ModifiedFile.cs", modifiedCode);

Quick Notes

  • If you use Roslyn for extraction, you can also use it to perform replacements (instead of regex) for absolute accuracy—traverse the syntax tree, rename identifiers, then generate the modified code string directly.
  • The regex approach works for simple code, but Roslyn is the way to go if you need to handle edge cases like nested code, lambda variables, or properties.

内容的提问来源于stack exchange,提问作者XazkerBoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:45:49