.Net MVC网站中配置文件的读写

所属分类: 网络编程 / ASP.NET 阅读数: 367
收藏 0 赞 0 分享

网站中有很多需要设置的内容,像网站信息,注册设置,上传设置等。如果保存在数据库中需要单独建张表,表中只有一条记录,这样会让数据库很臃肿,而且频繁存取数据库的效率也是个问题。而保存在config文件里是个不错选择,而且带有缓存功能! 

我们可以在web.config的配置节写入配置。 

<configuration>
 <configSections>
 <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
 <!--这里可以定义配置节 -->
 <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
 </configSections> 

但是把大量的配置都写入这里也会造成web.config的臃肿,可以采用把配置节定义在这里,把具体配置信息保存在其他文件中。 

以上传配置信息为例,看一下理想的结构 

Config\Upload.config的内容 

1、配置的元素。采用<add />的形式,是一个键和值得表示形式。<add key="MaxSize" value="1500000" />。 
2、元素的集合,里面定义一系列的元素。<UploadConfig>……</UploadConfig> 
3、自定义节,表示自定义的一个节点。<section name="UploadConfig"  type="Ninesky.Models.Config.UploadConfig, Ninesky.Models"/> 

name:节点名,type:处理节点的类行,逗号前是类名,逗号后是缩在程序集。

我们要创建这个类来管理配置 

一、创建键,值元素类。 

里面只有两个读写属性key和value,内容非常简单 

using System.Configuration;

namespace Ninesky.Models.Config
{
 /// <summary>
 /// 键值元素类
 /// <remarks>
 /// 创建:2014.03.09
 /// </remarks>
 /// </summary>
 public class KeyValueElement:ConfigurationElement
 {
  /// <summary>
  /// 键
  /// </summary>
  [ConfigurationProperty("key",IsRequired=true)]
  public string Key {
   get { return this["key"].ToString(); }
   set { this["key"] = value; }
  }
  /// <summary>
  /// 值
  /// </summary>
  [ConfigurationProperty("value")]
  public string Value
  {
   get { return this["value"].ToString(); }
   set { this["value"] = value; }
  }
 }
}

二、创建元素集合类。内容很简单都进行了注释 

using System;
using System.Configuration;

namespace Ninesky.Models.Config
{
 /// <summary>
 /// 元素集合类
 /// <remarks>
 /// 创建:2014.03.09
 /// </remarks>
 /// </summary>
 [ConfigurationCollection(typeof(KeyValueElement))]
 public class KeyValueElementCollection:ConfigurationElementCollection
 {
  //忽略大小写
  public KeyValueElementCollection() : base(StringComparer.OrdinalIgnoreCase) { }
  /// <summary>
  /// 集合中指定键的元素
  /// </summary>
  /// <param name="name"></param>
  /// <returns></returns>
  new public KeyValueElement this[string name]
  {
   get { return (KeyValueElement)base.BaseGet(name); }
   set
   {
    if (base.Properties.Contains(name)) base[name] = value;
    else base.BaseAdd(value);
   }
  }
  /// <summary>
  /// 创建新元素.
  /// 必须重写
  /// </summary>
  /// <returns></returns>
  protected override ConfigurationElement CreateNewElement()
  {
   return new KeyValueElement();
  }
  /// <summary>
  /// 获取元素的键
  /// </summary>
  /// <param name="element"></param>
  /// <returns></returns>
  protected override object GetElementKey(ConfigurationElement element)
  {
   return ((KeyValueElement)element).Key;
  }
 }
}

三、配置节类 

类中定义私有属性KeyValues。进行读写配置节集合,然后定义一系列的需要的配置属性,操作就是对KeyValues的元素读写。 

using System.Configuration;

namespace Ninesky.Models.Config
{
 /// <summary>
 /// 上传设置配置节
 /// <remarks>
 /// 创建:2014.03.09
 /// </remarks>
 /// </summary>
 public class UploadConfig:ConfigurationSection
 {
  private static ConfigurationProperty _property = new ConfigurationProperty(string.Empty, typeof(KeyValueElementCollection), null, ConfigurationPropertyOptions.IsDefaultCollection);
  /// <summary>
  /// 配置列表
  /// </summary>
  [ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
  private KeyValueElementCollection KeyValues
  {
   get { return (KeyValueElementCollection)base[_property]; }
   set { base[_property] = value; }
  }
  /// <summary>
  /// 最大大小
  /// </summary>
  public int MaxSize
  {
   get
   {
    int _value =0;
    if (KeyValues["MaxSize"] != null) int.TryParse(KeyValues["MaxSize"].Value, out _value);
    return _value;
   }
   set
   {
    if (KeyValues["MaxSize"] == null) KeyValues["MaxSize"] = new KeyValueElement() { Key = "MaxSize", Value = value.ToString() };
    else KeyValues["MaxSize"].Value = value.ToString();
   }
  }

  /// <summary>
  /// 上传目录
  /// 为应用程序目录起的文件夹名,前面不带~/
  /// </summary>
  public string Path
  {
   get
   {
    if (KeyValues["Path"] == null) return "Upload";
    return KeyValues["Path"].Value;
   }
   set
   {
    if (KeyValues["Path"] == null) KeyValues["Path"] = new KeyValueElement() { Key = "Path", Value = value };
    else KeyValues["Path"].Value = value;
   }
  }

  /// <summary>
  /// 允许上传的图片类型文件扩展,多个用“,”隔开
  /// </summary>
  public string ImageExt
  {
   get
   {
    if (KeyValues["ImageExt"] == null) return string.Empty;
    return KeyValues["ImageExt"].Value;
   }
   set
   {
    if (KeyValues["ImageExt"] == null) KeyValues["ImageExt"] = new KeyValueElement() { Key = "ImageExt", Value = value };
    else KeyValues["ImageExt"].Value = value;
   }
  }

  /// <summary>
  /// 允许上传的Flash类型文件扩展,多个用“,”隔开
  /// </summary>
  public string FlashExt
  {
   get
   {
    if (KeyValues["FlashExt"] == null) return string.Empty;
    return KeyValues["FlashExt"].Value;
   }
   set
   {
    if (KeyValues["FlashExt"] == null) KeyValues["FlashExt"] = new KeyValueElement() { Key = "FlashExt", Value = value };
    else KeyValues["FlashExt"].Value = value;
   }
  }

  /// <summary>
  /// 允许上传的媒体类型文件扩展,多个用“,”隔开
  /// </summary>
  public string MediaExt
  {
   get
   {
    if (KeyValues["MediaExt"] == null) return string.Empty;
    return KeyValues["MediaExt"].Value;
   }
   set
   {
    if (KeyValues["MediaExt"] == null) KeyValues["MediaExt"] = new KeyValueElement() { Key = "MediaExt", Value = value };
    else KeyValues["MediaExt"].Value = value;
   }
  }

  /// <summary>
  /// 允许上传的文件类型文件扩展,多个用“,”隔开
  /// </summary>
  public string FileExt
  {
   get
   {
    if (KeyValues["FileExt"] == null) return string.Empty;
    return KeyValues["FileExt"].Value;
   }
   set
   {
    if (KeyValues["FileExt"] == null) KeyValues["FileExt"] = new KeyValueElement() { Key = "FileExt", Value = value };
    else KeyValues["FileExt"].Value = value;
   }
  }
 }
}

四、读取配置 
也是最关系的,配置信息怎么读出来。在上面类写好后读取非常容易了,只需用WebConfigurationManager.OpenWebConfiguration("~"). GetSection()获取配置节的实例,局可以使用属性值了 

var _uploadConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~").GetSection("UploadConfig") as Ninesky.Models.Config.UploadConfig;
   //文件最大限制
   int _maxSize = _uploadConfig.MaxSize;
   //文件路径
   string _fileParth = _uploadConfig.Path ;
   string _dirName;
   //允许上传的类型
   Hashtable extTable = new Hashtable();
   extTable.Add("image", _uploadConfig.ImageExt);
   extTable.Add("flash", _uploadConfig.FileExt);
   extTable.Add("media", _uploadConfig.MediaExt);
   extTable.Add("file", _uploadConfig.FileExt);

五、写入配置
 跟读取类似,把属性值设置后save()一下,内容就会保存到Config\Upload.config中。 

代码如下: 

var _uploadConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~").GetSection("UploadConfig") as Ninesky.Models.Config.UploadConfig;
   //文件最大限制
   int _maxSize = _uploadConfig.MaxSize;
   _uploadConfig.FileExt = "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2";
   _uploadConfig.FlashExt = "swf,flv";
   _uploadConfig.ImageExt = "gif,jpg,jpeg,png,bmp";
   _uploadConfig.MediaExt = "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb";
   _uploadConfig.Path = "Upload";
   _uploadConfig.CurrentConfiguration.Save();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

ASP.NET 水晶报表打印功能实现代码

ASP.NET下的水晶报表打印,据我所知有以下几种办法可以打印
收藏 0 赞 0 分享

ASP.Net 图片存入数据库的实现代码

在很多时候,我们有这样的需求:把图片存入到数据库当中。在一些应用程序中,我们可能有一些敏感的资料,由于存储在文件系统(file system)中的东西,将很容易被某些用户盗取,所以这些数据不能存放在文件系统中。
收藏 0 赞 0 分享

让Silverlight 2.0动画动起来Making Silverlight 2.0 animation Start(不能运动原因)

Microsoft Expression Blend 2 制作动画个人感觉倒像3DMAX 可以自动捕捉关键帧
收藏 0 赞 0 分享

asp.net Reporting Service在Web Application中的应用

由于我们这个项目中使用微软的报表服务(Reporting Services)作为报表输出工具,本人也对它进行一点点研究,虽没有入木三分,但这点知识至少可以在大部分Reporting Service的场景中应用。
收藏 0 赞 0 分享

C# 文件上传 默认最大为4M的解决方法

.net中默只能上传小于4m的文件,大于4M将无法显示页面.那么如何设置来使imputfile能上传更大的文件呢
收藏 0 赞 0 分享

asp.net 购物车实现详细代码

asp.net 购物车实现详细代码
收藏 0 赞 0 分享

asp.net repeater实现批量删除时注册多选框id到客户端

repeater批量删除时注册多选框id到客户端的实现代码
收藏 0 赞 0 分享

asp.net aspnetpager分页统计时与实际不符的解决办法

最近分页方面根据实际需要修改了一些函数
收藏 0 赞 0 分享

iis 服务器应用程序不可用的解决方法

访问页面时提示 服务器应用程序不可用,大家可以按照下面的方法重新注册下,应该能好点
收藏 0 赞 0 分享

asp.net button 绑定多个参数

asp.net button 绑定多个参数的代码
收藏 0 赞 0 分享
查看更多