阅读web.config内容的最佳方式

时间:2009-03-16 12:24:36

标签: c# asp.net

我需要阅读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 个答案:

答案 0 :(得分:5)

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

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

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

答案 1 :(得分:-1)

使用asp.net api

System.Configuration.Configuration rootWebConfig1 =

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");
  }
}