簡體   English   中英

使用 c# 修改 web.config 的程序集部分中的值

[英]Modifying values in the assemblies section of web.config with c#

我需要想辦法為 web.config 文件中的程序集部分添加 CRUD(創建、讀取、更新和刪除)支持。

它可能看起來像這樣

<system.web>
    <compilation defaultLanguage="c#" debug="true" batch="false" targetFramework="4.0">
        <assemblies>
            <add assembly="System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
            <add assembly="System.Data.DataSetExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> 
        </assemblies>
    </compilation>
</system.web>

我試圖從這樣的事情開始

public bool AssemblyExist(string name)
{
    var webConfig = new ExeConfigurationFileMap { ExeConfigFilename = GlobalSettings.FullpathToRoot + "web.config" };
    var config = ConfigurationManager.OpenMappedExeConfiguration(webConfig, ConfigurationUserLevel.None);
    var assemblies = config.GetSection("system.web");

     // return true on match
    return assemblies.ElementInformation.Properties.Keys.Equals(name);
}

但它當然失敗了。

所以,我想要一個示例,展示如何實際獲取系統中的值。web > 編譯 > 程序集部分!

有什么建議嗎?

有一個名為 AssemblyInfo 的數據類型,其中的關鍵!

private bool AssemblyExist(string fullName)
{
    var config = WebConfigurationManager.OpenWebConfiguration("~");
    var compilationSection = (CompilationSection)config.GetSection("system.web/compilation");

    return compilationSection.Assemblies.Cast<AssemblyInfo>().Any(assembly => assembly.Assembly == fullName);
}

或者如果在 ubmraco 中使用它

private bool AssemblyExist(string fullName)
{
    var webConfig = new ExeConfigurationFileMap { ExeConfigFilename = GlobalSettings.FullpathToRoot + "web.config" };
    var config = ConfigurationManager.OpenMappedExeConfiguration(webConfig, ConfigurationUserLevel.None);
    var compilationSection = (CompilationSection)config.GetSection("system.web/compilation");

    return compilationSection.Assemblies.Cast<AssemblyInfo>().Any(assembly => assembly.Assembly == fullName);
}

像這樣稱呼它

AssemblyExist("System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089")

並添加一個程序集

private static void AddAssembly(string fullName)
{
    var config = WebConfigurationManager.OpenWebConfiguration("~");
    var compilationSection = (CompilationSection)config.GetSection("system.web/compilation");

    var myAssembly = new AssemblyInfo(fullName);
    compilationSection.Assemblies.Add(myAssembly);
    config.Save();
}

調用它

AddAssembly("System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");

切里奧

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM