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

如何用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:

1. Scanning Web Project Configuration Files

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}");
}
2. Scanning .NET DLLs for Hardcoded Configurations

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");
            }
        }
    }
}
Bonus Tips for Reliable Detection
  • 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.config or appsettings.Production.json—these can sometimes sneak into non-production builds.
  • Avoid file locks: For .NET Core/.NET 5+ DLLs, use AssemblyLoadContext instead of Assembly.LoadFrom to 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:10:21