在.NET控制台应用中如何通过非字符串操作加载编辑保存源码文件?
Got it, you want to load MyClass.cs as a structured "source code/class object" instead of dealing with raw strings or runtime reflection data — this is exactly what Roslyn (the .NET Compiler Platform) was designed for. It lets you parse, analyze, and manipulate C# source code as a syntax tree and semantic model, giving you access to the actual class structure, members, and metadata at the source level (no compilation required upfront for analysis).
Step 1: Set Up Dependencies
First, install the necessary NuGet packages for Roslyn:
Microsoft.CodeAnalysis.CSharpMicrosoft.CodeAnalysis.CSharp.Workspaces
Step 2: Load and Analyze Your Source File
Here’s a working code example that loads your MyClass.cs file, parses it into a structured syntax tree, and retrieves the class as a semantic symbol (your desired "class object"):
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.IO; using System.Linq; // Load the source file content (we read it only to parse into the syntax tree) var sourceFilePath = @"C:\YourPath\MyClass.cs"; var sourceCode = File.ReadAllText(sourceFilePath); // Parse the source into a syntax tree (structured representation of the code) var syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); // Create a compilation context (add references to system assemblies your code uses) var references = new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).Assembly.Location) }; var compilation = CSharpCompilation.Create( assemblyName: "TempAnalysisCompilation", syntaxTrees: new[] { syntaxTree }, references: references); // Get the semantic model (links syntax tree nodes to their semantic meaning) var semanticModel = compilation.GetSemanticModel(syntaxTree); // Find the first class declaration in the syntax tree var classSyntax = syntaxTree.GetRoot() .DescendantNodes() .OfType<ClassDeclarationSyntax>() .FirstOrDefault(); if (classSyntax != null) { // Get the semantic symbol for the class — this is your "class object" var classSymbol = semanticModel.GetDeclaredSymbol(classSyntax) as INamedTypeSymbol; // Now you can inspect the class's details without string hacks or reflection Console.WriteLine($"Class Name: {classSymbol.Name}"); Console.WriteLine($"Namespace: {classSymbol.ContainingNamespace.Name}"); Console.WriteLine("\nMembers:"); foreach (var member in classSymbol.GetMembers()) { Console.WriteLine($"- {member.Kind}: {member.Name} (Type: {member.GetType().Name})"); } }
Key Differences from Your Previous Approaches
- Not raw string operations: The syntax tree and semantic model represent code as structured nodes (e.g.,
ClassDeclarationSyntax,MethodDeclarationSyntax) with built-in properties for names, modifiers, parameters, etc. - Not reflection: Reflection works on compiled assemblies at runtime, while Roslyn operates on the source code directly — you don’t need to compile the code first, and you can access information that reflection can’t (like XML docs, unused variables, or syntax-specific details).
Bonus: Modify the Source Code
If you need to make changes to the class (like renaming it or adding a method), Roslyn lets you manipulate the syntax tree and generate updated source code:
// Rename the class var newClassSyntax = classSyntax.WithIdentifier(SyntaxFactory.Identifier("MyUpdatedClass")); var newRoot = syntaxTree.GetRoot().ReplaceNode(classSyntax, newClassSyntax); // Generate the updated source code string var updatedSource = newRoot.ToFullString(); // Save the changes back to a file File.WriteAllText(@"C:\YourPath\MyUpdatedClass.cs", updatedSource);
This approach gives you full control over the source code structure without having to manually parse or edit strings.
内容的提问来源于stack exchange,提问作者SventoryMang

