如何用C#编程读取DLL内容,检测未更新的环境配置
Absolutely! You can absolutely build a C# console app to scan .NET DLLs and published web project files for leftover production environment configurations—this is a common (and smart) way to catch environment misconfigurations before deployment. Let’s break down how to handle both file types:
Web projects typically store configs in files like web.config (for .NET Framework) or appsettings.json (for .NET Core/.NET 5+). You can read and parse these directly to check for production-specific values:
Example: Checking web.config for Production Connection Strings
Use the .NET Configuration API to load and inspect the XML-based config:
using Microsoft.Extensions.Configuration; using System; using System.IO; var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddXmlFile("web.config", optional: false, reloadOnChange: false); IConfiguration config = configBuilder.Build(); // Check connection strings for production keywords var connectionStrings = config.GetSection("connectionStrings").GetChildren(); foreach (var cs in connectionStrings) { string csValue = cs.Value; if (csValue.IndexOf("prod", StringComparison.OrdinalIgnoreCase) >= 0 || csValue.IndexOf("production", StringComparison.OrdinalIgnoreCase) >= 0) { Console.WriteLine($"⚠️ Found production connection string in web.config:"); Console.WriteLine($" Key: {cs.Key}"); Console.WriteLine($" Value: {csValue}\n"); } } // Check appSettings section too var appSettings = config.GetSection("appSettings").GetChildren(); foreach (var setting in appSettings) { string settingValue = setting.Value; if (settingValue.IndexOf("prod", StringComparison.OrdinalIgnoreCase) >= 0) { Console.WriteLine($"⚠️ Found production setting in web.config:"); Console.WriteLine($" Key: {setting.Key}"); Console.WriteLine($" Value: {settingValue}\n"); } }
Example: Checking appsettings.json
For JSON-based configs, use the same Configuration API with JSON support:
var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false); IConfiguration config = configBuilder.Build(); // Check API endpoints or database configs string apiUrl = config["ApiSettings:BaseUrl"]; if (!string.IsNullOrEmpty(apiUrl) && apiUrl.Contains("prod", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine($"⚠️ Production API URL found in appsettings.json: {apiUrl}"); }
DLLs might contain hardcoded production values (like constants, static fields, or embedded resources). You can use .NET Reflection to inspect the assembly’s types and values:
Example: Scanning a DLL for Production Keywords
using System; using System.Reflection; using System.Linq; string dllPath = @"C:\Path\To\Your\Published\Project.dll"; Assembly targetAssembly = Assembly.LoadFrom(dllPath); // Define your list of production-related keywords string[] prodKeywords = { "prod", "production", "live", "prod-api.example.com", "ProductionDB" }; foreach (Type type in targetAssembly.GetTypes()) { // Check static fields for string values foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic)) { if (field.FieldType == typeof(string)) { string fieldValue = field.GetValue(null) as string; if (!string.IsNullOrEmpty(fieldValue) && prodKeywords.Any(k => fieldValue.Contains(k, StringComparison.OrdinalIgnoreCase))) { Console.WriteLine($"⚠️ Production value found in DLL:"); Console.WriteLine($" Type: {type.FullName}"); Console.WriteLine($" Field: {field.Name}"); Console.WriteLine($" Value: {fieldValue}\n"); } } } // Check static properties foreach (PropertyInfo prop in type.GetProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic)) { if (prop.PropertyType == typeof(string) && prop.CanRead) { string propValue = prop.GetValue(null) as string; if (!string.IsNullOrEmpty(propValue) && prodKeywords.Any(k => propValue.Contains(k, StringComparison.OrdinalIgnoreCase))) { Console.WriteLine($"⚠️ Production value found in DLL:"); Console.WriteLine($" Type: {type.FullName}"); Console.WriteLine($" Property: {prop.Name}"); Console.WriteLine($" Value: {propValue}\n"); } } } }
- Expand your keyword list: Add environment-specific terms your team uses (like internal production domain names, specific connection string patterns).
- Handle config transforms: Don’t forget to check files like
web.Release.configorappsettings.Production.json—these can sometimes sneak into non-production builds. - Avoid file locks: For .NET Core/.NET 5+ DLLs, use
AssemblyLoadContextinstead ofAssembly.LoadFromto load the DLL without locking it for the duration of your app. - Scan embedded resources: Some projects store configs as embedded XML/JSON files—use
targetAssembly.GetManifestResourceNames()to list and read these resources.
内容的提问来源于stack exchange,提问作者Nick

