1.获取服务器绝对路径:
public static string GetMapPath(string strPath) { if (HttpContext.Current != null) { return HttpContext.Current.Server.MapPath(strPath); } else { strPath = strPath.Replace("/", "\\"); if (strPath.StartsWith("\\")) { strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\'); } return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath); } }
2.简单实例序列化:实体类增加特性:[Serializable],实用:
序列化:
public static void Save(object obj, string filename) { FileStream fs = null; try { fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(fs, obj); } catch (Exception ex) { throw ex; } finally { if (fs != null) fs.Close(); } }
反序列化:
public static object Load(Type type, string filename) { FileStream fs = null; try { fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); XmlSerializer serializer = new XmlSerializer(type); return serializer.Deserialize(fs); } catch (Exception ex) { throw ex; } finally { if (fs != null) fs.Close(); } }
3、URL字符编码:HttpContext.Current.Server.UrlEncode(str)、HttpContext.Current.Server.UrlDecode(str)
获取web.config中appSettings字节值:ConfigurationManager.AppSettings[xmlName].ToString()
4、int.TryParse与 int.Parse 又较为类似,但它不会产生异常,转换成功返回 true,转换失败返回 false。
最后一个参数为输出值,如果转换失败,输出值为 0,如果转换成功,输出值为转换后的int值
public GetInt(string str, int defaultValue) { int result = 0;
int.TryParse(str, out result);
return result == 0 ? defaultValue : result; }
5.对得到的值要有是否为空的判断
6、禁止回车表单自动提交:οnkeydοwn="if(event.keyCode==13){return false;}"
7、IO相关:
1)获取文件夹下文件: string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);
2)获取文件名:Path.GetFileNameWithoutExtension(file);
3)读取:string[] sqlItems = File.ReadAllLines(path); string text=FileExtend.ReadAllText(text);
Byte[] buff = File.ReadAllBytes(path); Encoding.Default.GetString(buff);
8、Request对象: [URL]:LocalPath:映射路径,[UrlReferrer]:PathAndQuery
Response:
9、Reflection:
Assembly ass = Assembly.Load(DllName);//完整DLL Type[] typeList = ass.GetExportedTypes(); Type:Name,FullName,BaseType
MethodInfo:Name,GetCustomAttributes
GetProperty().GetValue
实例化:object o = Activator.CreateInstance(t); t.GetMethod("ProcessRequest").Invoke(o, new object[] { });
10、WriteCookie
HttpCookie tokenCookie = new HttpCookie("name", value); tokenCookie.Domain = ; tokenCookie.Expires = DateTime.Now.AddHours(1); HttpContext.Current.Response.Cookies.Add(tokenCookie);
11、int补齐字符串:string.padledt(len,'0'); int.tostring("d8")