代码之家  ›  专栏  ›  技术社区  ›  Surgical Coder

读取web.config内容的最佳方法

  •  2
  • Surgical Coder  · 技术社区  · 17 年前

    我需要阅读web.config的内容并通过电子邮件发送它们,是否有更好的方法来执行以下操作:

            string webConfigContents = String.Empty;
            using (FileStream steam = new FileStream(
                     Server.MapPath("~/web.config"),
                     FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (StreamReader reader = new StreamReader(steam))
                {
                    webConfigContents = reader.ReadToEnd();
                }
            }
    

    我不想锁定文件。有什么想法吗?

    编辑-我需要一个文件的原始转储,我不能附加文件(webhost说不!)我不想在里面找什么特别的东西

    2 回复  |  直到 17 年前
        1
  •  5
  •   M4N    17 年前

    您可以用以下代码替换代码:

    string webConfigContents = File.ReadAllText(Server.MapPath("~/web.config"));
    

    文件在读取时将被锁定写入,但不用于读取。但我不认为这是个问题,因为web.config文件通常不会被写入(因为这样会重新启动web应用程序)。

        2
  •  -1
  •   Sander Versluys    17 年前

    通过使用 asp.net api .

    system.configuration.configuration根webconfig1=

    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
    if (0 < rootWebConfig1.AppSettings.Settings.Count)
    {
      System.Configuration.KeyValueConfigurationElement customSetting = 
      rootWebConfig1.AppSettings.Settings["customsetting1"];
      if (null != customSetting) {
        Console.WriteLine("customsetting1 application string = \"{0}\"",                  customSetting.Value);
      }
      else {
        Console.WriteLine("No customsetting1 application string");
      }
    }
    
    推荐文章