今天谈谈在.net中读写config文件的各种方法。 在这篇博客中,我将介绍各种配置文件的读写操作。 由于内容较为直观,因此没有过多的空道理,只有实实在在的演示代码, 目的只为了再现实战开发中的各种场景。希望大家能喜欢。 通常,我们在.NET开发过程中,会接触二种类型的配置文件:config文件,xml文件。 今天的博客示例也将介绍这二大类的配置文件的各类操作。 在config文件中,我将主要演示如何创建自己的自定义的配置节点,而不是介绍如何使用appSetting 。 请明:本文所说的config文件特指app.config或者web.config,而不是一般的XML文件。 在这类配置文件中,由于.net framework已经为它们定义了一些配置节点,因此我们并不能简单地通过序列化的方式去读写它。 config文件 – 自定义配置节点 为什么要自定义的配置节点? 确实,有很多人在使用config文件都是直接使用appSetting的,把所有的配置参数全都塞到那里,这样做虽然不错, 但是如果参数过多,这种做法的缺点也会明显地暴露出来:appSetting中的配置参数项只能按key名来访问,不能支持复杂的层次节点也不支持强类型, 而且由于全都只使用这一个集合,你会发现:完全不相干的参数也要放在一起! 想摆脱这种困扰吗?自定义的配置节点将是解决这个问题的一种可行方法。 首先,我们来看一下如何在app.config或者web.config中增加一个自定义的配置节点。 在这篇博客中,我将介绍4种自定义配置节点的方式,最终的配置文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="MySection111" type="RwConfigDemo.MySection1, RwConfigDemo" /> <section name="MySection222" type="RwConfigDemo.MySection2, RwConfigDemo" /> <section name="MySection333" type="RwConfigDemo.MySection3, RwConfigDemo" /> <section name="MySection444" type="RwConfigDemo.MySection4, RwConfigDemo" /> </configSections> <MySection111 username="fish-li" url="http://www.cnblogs.com/fish-li/"></MySection111> <MySection222> <users username="fish" password="liqifeng"></users> </MySection222> <MySection444> <add key="aa" value="11111"></add> <add key="bb" value="22222"></add> <add key="cc" value="33333"></add> </MySection444> <MySection333> <Command1> <![CDATA[ create procedure ChangeProductQuantity( @ProductID int, @Quantity int ) as update Products set Quantity = @Quantity where ProductID = @ProductID; ]]> </Command1> <Command2> <![CDATA[ create procedure DeleteCategory( @CategoryID int ) as delete from Categories where CategoryID = @CategoryID; ]]> </Command2> </MySection333> </configuration> |
同时,我还提供所有的示例代码(文章结尾处可供下载),演示程序的界面如下: config文件 – Property 先来看最简单的自定义节点,每个配置值以属性方式存在:
1 |
<MySection111 username="fish-li" url="http://www.cnblogs.com/fish-li/"></MySection111> |
实现代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class MySection1 : ConfigurationSection { [ConfigurationProperty("username", IsRequired = true)] public string UserName { get { return this["username"].ToString(); } set { this["username"] = value; } } [ConfigurationProperty("url", IsRequired = true)] public string Url { get { return this["url"].ToString(); } set { this["url"] = value; } } } |
小结: 1. 自定义一个类,以ConfigurationSection为基类,各个属性要加上[ConfigurationProperty] ,ConfigurationProperty的构造函数中传入的name字符串将会用于config文件中,表示各参数的属性名称。 2. 属性的值的读写要调用this[],由基类去保存,请不要自行设计Field来保存。 3. 为了能使用配置节点能被解析,需要在<configSections>中注册: <section name="MySection111" type="RwConfigDemo.MySection1, RwConfigDemo" /> ,且要注意name="MySection111"要与<MySection111 ….. >是对应的。 说明:下面将要介绍另三种配置节点,虽然复杂一点,但是一些基础的东西与这个节点是一样的,所以后面我就不再重复说明了。 config文件 – Element 再来看个复杂点的,每个配置项以XML元素的方式存在:
1 2 3 |
<MySection222> <users username="fish" password="liqifeng"></users> </MySection222> |
实现代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class MySection2 : ConfigurationSection { [ConfigurationProperty("users", IsRequired = true)] public MySectionElement Users { get { return (MySectionElement)this["users"]; } } } public class MySectionElement : ConfigurationElement { [ConfigurationProperty("username", IsRequired = true)] public string UserName { get { return this["username"].ToString(); } set { this["username"] = value; } } [ConfigurationProperty("password", IsRequired = true)] public string Password { get { return this["password"].ToString(); } set { this["password"] = value; } } } |
小结: 1. 自定义一个类,以ConfigurationSection为基类,各个属性除了要加上[ConfigurationProperty] 2. 类型也是自定义的,具体的配置属性写在ConfigurationElement的继承类中。 config文件 – CDATA 有时配置参数包含较长的文本,比如:一段SQL脚本,或者一段HTML代码,那么,就需要CDATA节点了。假设要实现一个配置,包含二段SQL脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<MySection333> <Command1> <![CDATA[ create procedure ChangeProductQuantity( @ProductID int, @Quantity int ) as update Products set Quantity = @Quantity where ProductID = @ProductID; ]]> </Command1> <Command2> <![CDATA[ create procedure DeleteCategory( @CategoryID int ) as delete from Categories where CategoryID = @CategoryID; ]]> </Command2> </MySection333> |
实现代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public class MySection3 : ConfigurationSection { [ConfigurationProperty("Command1", IsRequired = true)] public MyTextElement Command1 { get { return (MyTextElement)this["Command1"]; } } [ConfigurationProperty("Command2", IsRequired = true)] public MyTextElement Command2 { get { return (MyTextElement)this["Command2"]; } } } public class MyTextElement : ConfigurationElement { protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey) { CommandText = reader.ReadElementContentAs(typeof(string), null) as string; } protected override bool SerializeElement(System.Xml.XmlWriter writer, bool serializeCollectionKey) { if( writer != null ) writer.WriteCData(CommandText); return true; } [ConfigurationProperty("data", IsRequired = false)] public string CommandText { get { return this["data"].ToString(); } set { this["data"] = value; } } } |
小结: 1. 在实现上大体可参考MySection2, 2. 每个ConfigurationElement由我们来控制如何读写XML,也就是要重载方法SerializeElement,DeserializeElement config文件 – Collection
1 2 3 4 5 |
<MySection444> <add key="aa" value="11111"></add> <add key="bb" value="22222"></add> <add key="cc" value="33333"></add> </MySection444> |
这种类似的配置方式,在ASP.NET的HttpHandler, HttpModule中太常见了,想不想知道如何实现它们? 代码如下: 小结: 1. 为每个集合中的参数项创建一个从ConfigurationElement继承的派生类,可参考MySection1 2. 为集合创建一个从ConfigurationElementCollection继承的集合类,具体在实现时主要就是调用基类的方法。 3. 在创建ConfigurationSection的继承类时,创建一个表示集合的属性就可以了,注意[ConfigurationProperty]的各参数。 config文件 – […]
View Details在ASP.NET这样的Web应用中,Session是用来保存用户状态的常用手段,不过由于服务器内存空间是有限的,所以Session过期时间设置是很有必要的。在ASP.NET中如何设置Session的过期时间呢,很简单,修改web.config配置。 具体修改方法如下,在web.config中进行如下配置 1 2 3 <system.web> <sessionState mode="InProc" timeout="30"/> </system.web> 在这里指的是Session过期时间为30分钟。也就是说30分钟后如果当前用户没有操作,那么Session就会自动过期了。 from:http://www.cnblogs.com/sjrhero/archive/2010/10/15/1852449.html
View Details首先在Global.asax.cs里增加: protected void Application_PreSendRequestHeaders(object sender, EventArgs e) { HttpContext.Current.Response.Headers.Set("Server", "w3cnet.com"); HttpContext.Current.Response.Headers.Remove("X-AspNet-Version"); HttpContext.Current.Response.Cookies.Remove(".ASPXAUTH"); } 然后web.config的system.webServer节点下增加: <httpProtocol> <customHeaders> <remove name="X-Powered-By" /> </customHeaders> </httpProtocol> 再看看响应头,或用站长工具查看,完美隐藏。 参考资料: http://www.yn-s.com/news/Details/93
View Details1、指定表单提交方式和路径等
1 |
@using (Html.BeginForm("Index", "Home", FormMethod.Get, new { name = "nbform", id = "nbform" })) |
2、指定表单提交为数据方式
1 |
@using (Html.BeginForm("ImportExcel", "Stock", FormMethod.Post, new { enctype = "multipart/form-data" })) |
注意, 有时候要加{id=1}不然在点击超过第一页的索引时form后面会自动加上当前页的索引,如果此时再搜索则可能会出来“超出索引值”的错误提示 @using (Html.BeginForm("Index", null, new { id = 1 }, FormMethod.Get)) 3、下面的操作可以防止提交链接后面自带参数
1 |
@using (Html.BeginForm("AddDIYBillOfLading", "BillOfLading", new { id ="" }, FormMethod.Post, new { name = "myform", id = "myform" })) |
即,RouteValues的id="" from:http://www.cnblogs.com/firstcsharp/archive/2013/08/05/3238321.html
View DetailsJSON是专门为浏览器中的网页上运行的JavaScript代码而设计的一种数据格式。在网站应用中使用JSON的场景越来越多,本文介绍ASP.NET中JSON的序列化和反序列化,主要对JSON的简单介绍,ASP.NET如何序列化和反序列化的处理,在序列化和反序列化对日期时间、集合、字典的处理。 一、JSON简介 JSON(JavaScript Object Notation,JavaScript对象表示法)是一种轻量级的数据交换格式。 JSON是“名值对”的集合。结构由大括号'{}’,中括号'[]’,逗号’,’,冒号’:’,双引号’“”’组成,包含的数据类型有Object,Number,Boolean,String,Array, NULL等。 JSON具有以下的形式: 对象(Object)是一个无序的“名值对”集合,一个对象以”{”开始,”}”结束。每个“名”后跟着一个”:”,多个“名值对”由逗号分隔。如:
1 |
var user={"name":"张三","gender":"男","birthday":"1980-8-8"} |
数组(Array)是值的有序集合,一个数组以“[”开始,以“]”结束,值之间使用“,”分隔。如:
1 |
var userlist=[{"user":{"name":"张三","gender":"男","birthday":"1980-8-8"}},{"user":{"name":"李四","gender":"男","birthday":"1985-5-8"}}]; |
字符串(String)是由双引号包围的任意数量的Unicode字符的集合,使用反斜线转义。 二、对JSON数据进行序列化和反序列化 可以使用DataContractJsonSerializer类将类型实例序列化为JSON字符串,并将JSON字符串反序列化为类型实例。DataContractJsonSerializer在System.Runtime.Serialization.Json命名空间下,.NET Framework 3.5包含在System.ServiceModel.Web.dll中,需要添加对其的引用;.NET Framework 4在System.Runtime.Serialization中。 利用DataContractJsonSerializer序列化和反序列化的代码:
1 |
1: using System; |
1 |
2: using System.Collections.Generic; |
1 |
3: using System.Linq; |
1 |
4: using System.Web; |
1 |
5: using System.Runtime.Serialization.Json; |
1 |
6: using System.IO; |
1 |
7: using System.Text; |
1 |
8: |
1 |
9: /// <summary> |
1 |
10: /// JSON序列化和反序列化辅助类 |
1 |
11: /// </summary> |
1 |
12: public class JsonHelper |
1 |
13: { |
1 |
14: /// <summary> |
1 |
15: /// JSON序列化 |
1 |
16: /// </summary> |
1 |
17: public static string JsonSerializer<T>(T t) |
1 |
18: { |
1 |
19: DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); |
1 |
20: MemoryStream ms = new MemoryStream(); |
1 |
21: ser.WriteObject(ms, t); |
1 |
22: string jsonString = Encoding.UTF8.GetString(ms.ToArray()); |
1 |
23: ms.Close(); |
1 |
24: return jsonString; |
1 |
25: } |
1 |
26: |
1 |
27: /// <summary> |
1 |
28: /// JSON反序列化 |
1 |
29: /// </summary> |
1 |
30: public static T JsonDeserialize<T>(string jsonString) |
1 |
31: { |
1 |
32: DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); |
1 |
33: MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); |
1 |
34: T obj = (T)ser.ReadObject(ms); |
1 |
35: return obj; |
1 |
36: } |
1 |
37: } |
序列化Demo: 简单对象Person:
1 |
1: public class Person |
1 |
2: { |
1 |
3: public string Name { get; set; } |
1 |
4: public int Age { get; set; } |
1 |
5: } |
序列化为JSON字符串:
1 |
1: protected void Page_Load(object sender, EventArgs e) |
1 |
2: { |
1 |
3: Person p = new Person(); |
1 |
4: p.Name = "张三"; |
1 |
5: p.Age = 28; |
1 |
6: |
1 |
7: string jsonString = JsonHelper.JsonSerializer<Person>(p); |
1 |
8: Response.Write(jsonString); |
1 |
9: } |
输出结果:
1 |
{"Age":28,"Name":"张三"} |
反序列化Demo:
1 |
1: protected void Page_Load(object sender, EventArgs e) |
1 |
2: { |
1 |
3: string jsonString = "{\"Age\":28,\"Name\":\"张三\"}"; |
1 |
4: Person p = JsonHelper.JsonDeserialize<Person>(jsonString); |
1 |
5: } |
运行结果: ASP.NET中的JSON序列化和反序列化还可以使用JavaScriptSerializer,在System.Web.Script.Serializatioin命名空间下,需引用System.Web.Extensions.dll.也可以使用JSON.NET. […]
View Detailsusing System; using System.Collections.Generic; using System.Text; namespace NET.MST.Fourth.StringByte { class StringByte { static void Main(string[] args) { String s = "我是字符串,I am string"; //字节数组转换到字符串 Byte[] utf8 = StringToByte(s, Encoding.UTF8); Byte[] gb2312 = StringToByte(s, Encoding.GetEncoding("GB2312")); Byte[] unicode = StringToByte(s, Encoding.Unicode); Console.WriteLine(utf8.Length); Console.WriteLine(gb2312.Length); Console.WriteLine(unicode.Length); //转换回字符串 Console.WriteLine(ByteToString(utf8, Encoding.UTF8)); Console.WriteLine(ByteToString(gb2312, Encoding.GetEncoding("GB2312"))); Console.WriteLine(ByteToString(unicode, Encoding.Unicode)); Console.Read(); } static Byte[] StringToByte(String s, Encoding encoding) { return encoding.GetBytes(s); } static String ByteToString(Byte[] b, Encoding encoding) { return encoding.GetString(b); } } } from:http://www.cnblogs.com/brainmao/archive/2011/05/29/2062385.html
View Details介绍 让用户从我们的网站上下载各种类型的文件是一个比较常用的功能,这篇文章就是告诉您如何创建一个.txt文件并让用户下载。 使用代码 虽然在示例里,我先创建了一个text文件,但是你不一定也要这么做,因为这个文件可能在你的网站里已经存在了。如果是这样的话,你只需要使用FileStream去读取它就可以了。 首先,我们将这个text文件读取到一个byte数组中,然后使用Response对象将文件写到客户端就可以了。 Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName); Response.ContentType = "application/octet-stream"; Response.BinaryWrite(btFile); Response.End(); 这段代码是完成这个功能的主要代码。第一句在输出中添加了一个Header,告诉浏览器我们发送给它的是一个附件类型的文件。然后我们设置输出的ContentType是"application/octet-stream",即告诉浏览器要下载这个文件,而不是在浏览器中显示它。 下面是一个MIME类型的列表。 ".asf" = "video/x-ms-asf" ".avi" = "video/avi" ".doc" = "application/msword" ".zip" = "application/zip" ".xls" = "application/vnd.ms-excel" ".gif" = "image/gif" ".jpg"= "image/jpeg" ".wav" = "audio/wav" ".mp3" = "audio/mpeg3" ".mpg" "mpeg" = "video/mpeg" ".rtf" = "application/rtf" ".htm", "html" = "text/html" ".asp" = "text/asp" '所有其它的文件 = "application/octet-stream" 下面是一个完整的如何下载文本文件的示例代码 C# protected void Button1_Click(object sender, EventArgs e) { string sFileName = System.IO.Path.GetRandomFileName(); string sGenName = "Friendly.txt"; //YOu could omit these lines here as you may not want […]
View DetailsIIS上部署MVC网站,打开后ExtensionlessUrlHandler-Integrated-4.0解决方法 IIS上部署MVC网站,打开后500错误:处理程序“ExtensionlessUrlHandler-Integrated-4.0”在其模块列表中有一个错误模块“ManagedPipelineHandler” 解决方法如下: 以管理员运行下面的命令注册: 32位机器: C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i 64位机器: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
View Details最近新换了系统还真是问题多多呀!! 系统更新补丁后打开 VS2012 ,新建C#项目的时候出现这个问题 VS2012 未找到与约束ContractName Microsoft.VisualStudio.Text.ITextDoc mentFactoryService 我勒个去,相当郁闷呀,赶紧百度,找到了下面两个解决方案: 方案一: 删除 kb2805222 .net4.5 framework 更新程序(控制面板->Windows Update->) 但是我这里没有这个更新 于是我采用第二套方案 方案二: 更新 (KB2781514) 下载网址:http://www.microsoft.com/zh-cn/download/confirmation.aspx?id=36020 OK了!哈哈~~~~ from:http://www.cnblogs.com/csulennon/p/3709019.html
View Details