【转载】asp.net项目总结

学习.NET有一些时间了,平日积累了一些自己认为比较实用的方法(有自己写的,也有学习别人的),可能会在不同的项目开发中使用到。分享给大家,有什么好的方法还会不断添加,个别方法你可能认为很菜,仅提供给新手。当然,实现功能的方法并不唯一,这里仅供大家参考。

修改配置文件

Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);    //创建配置文件对象
config.AppSettings.Settings[KEY].Value=VALUE;    //设置KEY的值为VALUE
config.Save(ConfigurationSaveMode.Modified);    //保存设置
ConfigurationManager.RefreshSection("appSettings");    //刷新设置

 

将文件转换成字符串,常用于读取网站模板


/// <summary>
    
/// 将文件转换成字符串,常用于读取网站模板
    
/// </summary>
    
/// <param name="path"></param>
    
/// <param name="isSpace"></param>
    
/// <returns></returns>
    public static string GetTempleContent(string path)
    {
        
string result = string.Empty;
        
string sFileName = HttpContext.Current.Server.MapPath(path);
        
if (File.Exists(sFileName))
        {
            
try
            {
                
using (StreamReader sr = new StreamReader(sFileName))
                {
                    result 
= sr.ReadToEnd();
                }
            }
            
catch
            {
                result 
= "读取模板文件(" + path + ")出错";
            }
        }
        
else
        {
            result 
= "找不到模板文件:" + path;
        }
        
return result;
    }

读取,添加,修改xml文件


/// <summary>
    
/// 读取,添加,修改xml文件
    
/// </summary>
    
/// <param name="Xmlpath">Xml路径</param>
    
/// <param name="Node">新的子节点名称</param>
    
/// <param name="Value">新节点对应的值</param>
    
/// <param name="flag">1:读取,否则为 修改或者添加</param>
    
/// <returns>1:修改添加成功,为空字符串表示修改添加成功,否则是读取成功</returns>
    public static string getXML(string Xmlpath, string Node, string Value, int flag)
    {
        
try
        {
            
string filepath = HttpContext.Current.Server.MapPath(Xmlpath);
            XmlDocument xmlDoc 
= new XmlDocument();
            
if (!File.Exists(filepath))
            {
                XmlDeclaration xn 
= xmlDoc.CreateXmlDeclaration("1.0""utf-8"null);
                XmlElement root 
= xmlDoc.CreateElement("rss");
                XmlElement root1 
= xmlDoc.CreateElement("item");

                root.AppendChild(root1);
                xmlDoc.AppendChild(xn);
                xmlDoc.AppendChild(root);
                xmlDoc.Save(filepath);
//本地路径名字
            }
            xmlDoc.Load(filepath);
//你的xml文件
            string ReStr = string.Empty;
            XmlElement xmlObj 
= xmlDoc.DocumentElement;

            XmlNodeList xmlList 
= xmlDoc.SelectSingleNode(xmlObj.Name.ToString()).ChildNodes;

            
foreach (XmlNode xmlNo in xmlList)
            {
                
if (xmlNo.NodeType != XmlNodeType.Comment)//判断是不是注释类型
                {
                    XmlElement xe 
= (XmlElement)xmlNo;
                    {
                        
if (xe.Name == xmlObj.FirstChild.Name)
                        {
                            XmlNodeList xmlNList 
= xmlObj.FirstChild.ChildNodes;

                            
foreach (XmlNode xmld in xmlNList)
                            {
                                XmlElement xe1 
= (XmlElement)xmld;
                                {
                                    
if (xe1.Name == Node)
                                    {
                                        
if (flag == 1)//读取值
                                        {
                                            
if (xmld.InnerText != null && xmld.InnerText != "")
                                            {
                                                ReStr 
= xmld.InnerText;
                                            }
                                        }
                                        
else//修改值
                                        {
                                            xmld.InnerText 
= Value;//给节点赋值
                                            xmlDoc.Save(filepath);
                                            ReStr 
= Value.Trim();
                                        }
                                    }
                                }
                            }
                            
if (ReStr == string.Empty)// 添加节点
                            {
                                XmlNode newNode;
                                newNode 
= xmlDoc.CreateNode("element", Node, Value);//创建节点
                                newNode.InnerText = Value;//给节点赋值
                                xe.AppendChild(newNode);//把节点添加到doc
                                xmlDoc.Save(filepath);
                                ReStr 
= Value.Trim();
                            }
                        }
                    }
                }
            }
            
return ReStr;
        }
        
catch
        {
            
return string.Empty;
        }
    }

取得文件扩展名


/// <summary>
    
/// 取得文件扩展名
    
/// </summary>
    
/// <param name="filename">文件名</param>
    
/// <returns>扩展名</returns>
    public static string GetFileEXT(string filename)
    {
        
if (string.IsNullOrEmpty(filename))
        {
            
return "";
        }
        
if (filename.IndexOf(@"."== -1)
        {
            
return "";
        }
        
int pos = -1;
        
if (!(filename.IndexOf(@"\"== -1))
        {
            pos 
= filename.LastIndexOf(@"\");
        }
        
string[] s = filename.Substring(pos + 1).Split('.');
        
return s[1];
    }

替换文本中的空格和换行


/// <summary>
    
/// 替换文本中的空格和换行
    
/// </summary>
    public static string ReplaceSpace(string str)
    {
        
string s = str;
        s 
= s.Replace(" ""&nbsp;");
        s 
= s.Replace("\n""<BR />");
        
return s;
    }

验证码实现方法


    protected void Page_Load(object sender, EventArgs e)
    {
         
string checkCode = CreateRandomCode(4);
          Session[
"CheckCode"= checkCode;
          CreateImage(checkCode);
    }
     
private string CreateRandomCode(int codeCount)
    {

        
// 函数功能:产生数字和字符混合的随机字符串
        string allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        
char[] allCharArray = allChar.ToCharArray();
        
string randomCode = "";
        Random rand 
= new Random();
        
for (int i = 0; i < codeCount; i++)
        {
           
int r=rand.Next(61);
           randomCode
+=allCharArray.GetValue(r);
        }
         
return randomCode;
        
     }
         

    
private void CreateImage(string checkCode)
    {

        
// 生成图象验证码函数
       int iwidth = (int)(checkCode.Length * 11.5);
        System.Drawing.Bitmap image 
= new System.Drawing.Bitmap(iwidth, 20);
        Graphics g 
= Graphics.FromImage(image);
        Font f 
= new System.Drawing.Font("Arial"10, System.Drawing.FontStyle.Bold);
        Brush b 
= new System.Drawing.SolidBrush(Color.Azure);//字母白色
        
//g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
        g.Clear(Color.Brown);//背景灰色
        g.DrawString(checkCode, f, b, 33);

        Pen blackPen 
= new Pen(Color.Black, 0);
        Random rand 
= new Random();
        System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        Response.ClearContent();
        Response.ContentType 
= "image/Jpeg";
        Response.BinaryWrite(ms.ToArray());
        g.Dispose();
        image.Dispose();
    }

文件创建、复制、移动、删除


FileStream fs;
 
//创建文件
 fs = File.Create(Server.MapPath("a.txt"));
 fs.Close();
 fs 
= File.Create(Server.MapPath("b.txt"));
 fs.Close();
 fs 
= File.Create(Server.MapPath("c.txt"));
 fs.Close();
 
//复制文件
 File.Copy(Server.MapPath("a.txt"), Server.MapPath("a\\a.txt"));
 
//移动文件
 File.Move(Server.MapPath("b.txt"), Server.MapPath("a\\b.txt"));
 File.Move(Server.MapPath(
"c.txt"), Server.MapPath("a\\c.txt"));
 
//删除文件
 File.Delete(Server.MapPath("a.txt"));

去掉结尾,


/// <summary>
    
/// 去掉结尾,
    
/// </summary>
    
/// <param name="input"></param>
    
/// <returns></returns>
    public static string LostDot(string input)
    {
        
if (string.IsNullOrEmpty(input))
        {
            
return string.Empty;
        }
        
else
        {
            
if (input.IndexOf(","> -1)
            {
                
int intLast = input.LastIndexOf(",");
                
if ((intLast + 1== input.Length)
                {
                    
return input.Remove(intLast);
                }
                
else
                {
                    
return input;
                }
            }
            
else
            {
                
return input;
            }
        }
    }

生成任意位数的随机数


/// <summary>
    
/// 生成随机数
    
/// </summary>
    
/// <param name="minValue">最小值</param>
    
/// <param name="maxValue">最大值</param>
    
/// <returns></returns>
    private int getRandom(int minValue, int maxValue)
    {
        Random ri 
= new Random(unchecked((int)DateTime.Now.Ticks));
        
int k = ri.Next(minValue, maxValue);
        
return k;
    }

//想定一个三位的随机数:string ThreeRandom=this.getRandom(100,999).Tostring();
//类似的,四位随机数:string FourRandom=this.getRandom(1000,9999).Tostring();

实现文件的上传


public class Upload
    {
        
private System.Web.HttpPostedFile postedFile = null;
        
private string savePath = "";
        
private string extension = "";
        
private int fileLength = 0;
        
private string filename = "";
        
/// <summary>
        
/// 上传组件
        
/// </summary>
        public System.Web.HttpPostedFile PostedFile
        {
            
get
            {
                
return postedFile;
            }
            
set
            {
                postedFile 
= value;
            }
        }
        
/// <summary>
        
/// 保存路径
        
/// </summary>
        public string SavePath
        {
            
get
            {
                
if (savePath != ""return savePath;
                
return "c:\\";
            }
            
set
            {
                savePath 
= value;
            }
        }
        
/// <summary>
        
/// 文件大小
        
/// </summary>
        public int FileLength
        {
            
get
            {
                
if (fileLength != 0return fileLength;
                
return 1024;
            }
            
set
            {
                fileLength 
= value * 1024;
            }
        }
        
/// <summary>
        
/// 文件护展名
        
/// </summary>
        public string Extension
        {
            
get
            {
                
if (extension != "")
                    
return extension;
                
return "txt";
            }
            
set
            {
                extension 
= value;
            }
        }
        
/// <summary>
        
/// 文件名
        
/// </summary>
        public string FileName
        {
            
get
            {
                
return filename;
            }
            
set
            {
                filename 
= value;
            }
        }
        
public string PathToName(string path)
        {
            
int pos = path.LastIndexOf(@"\");
            
return path.Substring(pos + 1);
        }
        
/// <summary>
        
/// 上传文件
        
/// </summary>
        
/// <returns></returns>
        public string UploadStart()
        {
            
bool tf = false;
            
string returnvalue = "";
            
if (PostedFile != null)
            {
                
try
                {
                    
string fileName = PathToName(PostedFile.FileName);
                    
if (filename != "")
                    {
                        fileName 
= filename;
                    }
                    
string _fileName = "";

                    
string[] Exten = Extension.Split(',');
                    
if (Exten.Length == 0)
                    {
                        returnvalue 
= "你未设置上传文件类型,系统不允许进行下一步操作!";
                    }
                    
else
                    {
                        
for (int i = 0; i < Exten.Length; i++)
                        {
                            
if (fileName.ToLower().EndsWith(Exten[i].ToLower()))
                            {
                                
if (PostedFile.ContentLength > FileLength)
                                {
                                    returnvalue 
= "上传文件限制大小:" + FileLength / 1024 + "kb!";
                                }
                                
string IsFileex = SavePath + @"\" + fileName;
                                
if (!Directory.Exists(SavePath)) { Directory.CreateDirectory(SavePath); }
                                PostedFile.SaveAs(IsFileex);
                                _fileName 
= fileName;
                                tf 
= true;
                                returnvalue 
= IsFileex ;
                            }
                        }
                        
if (tf == false)
                            returnvalue 
= "只允许上传" + Extension + " 文件!";
                    }
                }
                
catch (System.Exception exc)
                {
                    returnvalue 
= exc.Message;
                }
            }
            
else
            {
                returnvalue 
= "上文件失败!";
            }
            
return returnvalue;
        }
    }

判断输入是否为日期类型


 /// <summary>
        
/// 判断输入是否为日期类型
        
/// </summary>
        
/// <param name="s">待检查数据</param>
        
/// <returns></returns>
        public static bool IsDate(string s)
        {
            
if (s == null)
            {
                
return false;
            }
            
else
            {
                
try
                {
                    DateTime d 
= DateTime.Parse(s);
                    
return true;
                }
                
catch
                {
                    
return false;
                }
            }
        }

MD5加密字符串处理


/// <summary>
        
/// MD5加密字符串处理
        
/// </summary>
        
/// <param name="Half">加密是16位还是32位;如果为true为16位</param>
        public static string MD5(string Input, bool Half)
        {
            
string output = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Input, "MD5").ToLower();
            
if (Half) output = output.Substring(816);
            
return output;
        }

        
public static string MD5(string Input)
        {
            
return MD5(Input, true);
        }

过滤非法字符,防止注入式攻击等


/// <summary>
        
/// 过滤字符
        
/// </summary>
        public static string Filter(string sInput)
        {
            
if (sInput == null || sInput.Trim() == string.Empty)
                
return null;
            
string sInput1 = sInput.ToLower();
            
string output = sInput;
            
string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
            
if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.Compiled | RegexOptions.IgnoreCase).Success)
            {
                
throw new Exception("字符串中含有非法字符!");
            }
            
else
            {
                output 
= output.Replace("'""''");
            }
            
return output;
        }

常用的加密解密(DES,RSA)


    using System.Security.Cryptography;
using System.Text;

    
/// <summary>
    
/// DES加密
    
/// </summary>
    
/// <param name="input">待加密的字符串</param>
    
/// <param name="key">加密密钥</param>
    
/// <returns></returns>
    public static string Encrypt(string EncryptString, byte[] Key, byte[] IV)
    {
        
//byte[] rgbKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
        byte[] inputByteArray = Encoding.UTF8.GetBytes(EncryptString);
        DESCryptoServiceProvider des 
= new DESCryptoServiceProvider();
        MemoryStream mStream 
= new MemoryStream();
        CryptoStream cStream 
= new CryptoStream(mStream, des.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
        cStream.Write(inputByteArray, 
0, inputByteArray.Length);
        cStream.FlushFinalBlock();
        
return Convert.ToBase64String(mStream.ToArray());
    }
    
/// <summary>
    
/// DES解密
    
/// </summary>
    
/// <param name="input">待解密的字符串</param>
    
/// <param name="key">解密密钥,要求为8位,和加密密钥相同</param>
    
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
    public static string Decrypt(string DecryptString, byte[] Key, byte[] IV)
    {
        
try
        {
            
//byte[] rgbKey = Encoding.UTF8.GetBytes(Key);
            byte[] inputByteArray = Convert.FromBase64String(DecryptString);
            DESCryptoServiceProvider des 
= new DESCryptoServiceProvider();

            MemoryStream mStream 
= new MemoryStream();
            CryptoStream cStream 
= new CryptoStream(mStream, des.CreateDecryptor(Key, IV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 
0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            
return Encoding.UTF8.GetString(mStream.ToArray());
        }
        
catch
        {
            
return "";
        }
    }
}
/// <summary>
/// RSA加解密算法
/// </summary>
public class RSA
{
    
/// <summary>
    
/// RSA加密函数
    
/// </summary>
    
/// <param name="xmlPublicKey">说明KEY必须是XML的行式,返回的是字符串</param>
    
/// <param name="EncryptString"></param>
    
/// <returns></returns>
    public string Encrypt(string xmlPublicKey, string EncryptString)
    {
        
byte[] PlainTextBArray;
        
byte[] CypherTextBArray;
        
string Result;
        RSACryptoServiceProvider rsa 
= new RSACryptoServiceProvider();
        rsa.FromXmlString(xmlPublicKey);
        PlainTextBArray 
= (new UnicodeEncoding()).GetBytes(EncryptString);
        CypherTextBArray 
= rsa.Encrypt(PlainTextBArray, false);
        Result 
= Convert.ToBase64String(CypherTextBArray);
        
return Result;
    }
    
/// <summary>
    
/// RSA解密函数
    
/// </summary>
    
/// <param name="xmlPrivateKey"></param>
    
/// <param name="DecryptString"></param>
    
/// <returns></returns>
    public string Decrypt(string xmlPrivateKey, string DecryptString)
    {
        
byte[] PlainTextBArray;
        
byte[] DypherTextBArray;
        
string Result;
        RSACryptoServiceProvider rsa 
= new RSACryptoServiceProvider();
        rsa.FromXmlString(xmlPrivateKey);
        PlainTextBArray 
= Convert.FromBase64String(DecryptString);
        DypherTextBArray 
= rsa.Decrypt(PlainTextBArray, false);
        Result 
= (new UnicodeEncoding()).GetString(DypherTextBArray);
        
return Result;
    }

    
/// <summary>
    
/// 产生RSA的密钥
    
/// </summary>
    
/// <param name="xmlKeys">私钥</param>
    
/// <param name="xmlPublicKey">公钥</param>
    public void RSAKey(out string xmlKeys, out string xmlPublicKey)
    {
        RSACryptoServiceProvider rsa 
= new RSACryptoServiceProvider();
        xmlKeys 
= rsa.ToXmlString(true);
        xmlPublicKey 
= rsa.ToXmlString(false);
    }

写入读取Cookie值


/// <summary>
        
/// 写cookie值
        
/// </summary>
        
/// <param name="strName">名称</param>
        
/// <param name="strValue"></param>
        
/// <param name="strValue">过期时间(分钟)</param>
        public static void WriteCookie(string strName, string strValue, int expires)
        {
            HttpCookie cookie 
= HttpContext.Current.Request.Cookies[strName];
            
if (cookie == null)
            {
                cookie 
= new HttpCookie(strName);
            }
            cookie.Value 
= strValue;
            cookie.Expires 
= DateTime.Now.AddMinutes(expires);
            HttpContext.Current.Response.AppendCookie(cookie);
        }
        
/// <summary>
        
/// 读cookie值
        
/// </summary>
        
/// <param name="strName">名称</param>
        
/// <returns>cookie值</returns>
        public static string GetCookie(string strName)
        {
            
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
            {
                
return HttpContext.Current.Request.Cookies[strName].Value.ToString();
            }
            
return "";
        }

读取配置文件的节点内容


/// <summary>
        
/// 读取配置文件
        
/// </summary>
        
/// <param name="Target"></param>
        
/// <param name="ConfigPathName"></param>
        
/// <returns></returns>
        static internal string GetConfigValue(string Target, string XmlPath)
        {
            System.Xml.XmlDocument xdoc 
= new XmlDocument();
            xdoc.Load(XmlPath);
            XmlElement root 
= xdoc.DocumentElement;
            XmlNodeList elemList 
= root.GetElementsByTagName(Target);
            
return elemList[0].InnerXml;
        }

取单个字符的拼音声母


/// <summary> 
        
/// 取单个字符的拼音声母 
        
/// </summary> 
        
/// <param name="c">要转换的单个汉字</param> 
        
/// <returns>拼音声母</returns> 
        private static string GetPYChar(string c)
        {
            
byte[] array = new byte[2];
            array 
= System.Text.Encoding.Default.GetBytes(c);
            
int i = (short)(array[0- '\0'* 256 + ((short)(array[1- '\0'));
            
if (i < 0xB0A1return "*";
            
if (i < 0xB0C5return "A";
            
if (i < 0xB2C1return "B";
            
if (i < 0xB4EEreturn "C";
            
if (i < 0xB6EAreturn "D";
            
if (i < 0xB7A2return "E";
            
if (i < 0xB8C1return "F";
            
if (i < 0xB9FEreturn "G";
            
if (i < 0xBBF7return "H";
            
if (i < 0xBFA6return "G";
            
if (i < 0xC0ACreturn "K";
            
if (i < 0xC2E8return "L";
            
if (i < 0xC4C3return "M";
            
if (i < 0xC5B6return "N";
            
if (i < 0xC5BEreturn "O";
            
if (i < 0xC6DAreturn "P";
            
if (i < 0xC8BBreturn "Q";
            
if (i < 0xC8F6return "R";
            
if (i < 0xCBFAreturn "S";
            
if (i < 0xCDDAreturn "T";
            
if (i < 0xCEF4return "W";
            
if (i < 0xD1B9return "X";
            
if (i < 0xD4D1return "Y";
            
if (i < 0xD7FAreturn "Z";
            
return "*";
        }

变量.ToString()


   //字符型转换 转为字符串  
   12345.ToString("n");        //生成   12,345.00  
   12345.ToString("C");        //生成 ¥12,345.00  
   12345.ToString("e");        //生成 1.234500e+004  
   12345.ToString("f4");        //生成 12345.0000  
   12345.ToString("x");         //生成 3039  (16进制)  
   12345.ToString("p");         //生成 1,234,500.00%  

时间的处理


DateTime dt = DateTime.Now;
Label1.Text 
= dt.ToString();//2005-11-5 13:21:25
Label2.Text = dt.ToFileTime().ToString();//127756416859912816
Label3.Text = dt.ToFileTimeUtc().ToString();//127756704859912816
Label4.Text = dt.ToLocalTime().ToString();//2005-11-5 21:21:25
Label5.Text = dt.ToLongDateString().ToString();//2005年11月5日
Label6.Text = dt.ToLongTimeString().ToString();//13:21:25
Label7.Text = dt.ToOADate().ToString();//38661.5565508218
Label8.Text = dt.ToShortDateString().ToString();//2005-11-5
Label9.Text = dt.ToShortTimeString().ToString();//13:21
Label10.Text = dt.ToUniversalTime().ToString();//2005-11-5 5:21:25
?2005-11-5 13:30:28.4412864
Label1.Text 
= dt.Year.ToString();//2005
Label2.Text = dt.Date.ToString();//2005-11-5 0:00:00
Label3.Text = dt.DayOfWeek.ToString();//Saturday
Label4.Text = dt.DayOfYear.ToString();//309
Label5.Text = dt.Hour.ToString();//13
Label6.Text = dt.Millisecond.ToString();//441
Label7.Text = dt.Minute.ToString();//30
Label8.Text = dt.Month.ToString();//11
Label9.Text = dt.Second.ToString();//28
Label10.Text = dt.Ticks.ToString();//632667942284412864
Label11.Text = dt.TimeOfDay.ToString();//13:30:28.4412864
Label1.Text = dt.ToString();//2005-11-5 13:47:04
Label2.Text = dt.AddYears(1).ToString();//2006-11-5 13:47:04
Label3.Text = dt.AddDays(1.1).ToString();//2005-11-6 16:11:04
Label4.Text = dt.AddHours(1.1).ToString();//2005-11-5 14:53:04
Label5.Text = dt.AddMilliseconds(1.1).ToString();//2005-11-5 13:47:04
Label6.Text = dt.AddMonths(1).ToString();//2005-12-5 13:47:04
Label7.Text = dt.AddSeconds(1.1).ToString();//2005-11-5 13:47:05
Label8.Text = dt.AddMinutes(1.1).ToString();//2005-11-5 13:48:10
Label9.Text = dt.AddTicks(1000).ToString();//2005-11-5 13:47:04
Label10.Text = dt.CompareTo(dt).ToString();//0
//Label11.Text = dt.Add(?).ToString();//问号为一个时间段
Label1.Text = dt.Equals("2005-11-6 16:11:04").ToString();//False
Label2.Text = dt.Equals(dt).ToString();//True
Label3.Text = dt.GetHashCode().ToString();//1474088234
Label4.Text = dt.GetType().ToString();//System.DateTime
Label5.Text = dt.GetTypeCode().ToString();//DateTime

Label1.Text 
= dt.GetDateTimeFormats('s')[0].ToString();//2005-11-05T14:06:25
Label2.Text = dt.GetDateTimeFormats('t')[0].ToString();//14:06
Label3.Text = dt.GetDateTimeFormats('y')[0].ToString();//2005年11月
Label4.Text = dt.GetDateTimeFormats('D')[0].ToString();//2005年11月5日
Label5.Text = dt.GetDateTimeFormats('D')[1].ToString();//2005 11 05
Label6.Text = dt.GetDateTimeFormats('D')[2].ToString();//星期六 2005 11 05
Label7.Text = dt.GetDateTimeFormats('D')[3].ToString();//星期六 2005年11月5日
Label8.Text = dt.GetDateTimeFormats('M')[0].ToString();//11月5日
Label9.Text = dt.GetDateTimeFormats('f')[0].ToString();//2005年11月5日 14:06
Label10.Text = dt.GetDateTimeFormats('g')[0].ToString();//2005-11-5 14:06
Label11.Text = dt.GetDateTimeFormats('r')[0].ToString();//Sat, 05 Nov 2005 14:06:25 GMT

Label1.Text 
=? string.Format("{0:d}",dt);//2005-11-5
Label2.Text =? string.Format("{0:D}",dt);//2005年11月5日
Label3.Text =? string.Format("{0:f}",dt);//2005年11月5日 14:23
Label4.Text =? string.Format("{0:F}",dt);//2005年11月5日 14:23:23
Label5.Text =? string.Format("{0:g}",dt);//2005-11-5 14:23
Label6.Text =? string.Format("{0:G}",dt);//2005-11-5 14:23:23
Label7.Text =? string.Format("{0:M}",dt);//11月5日
Label8.Text =? string.Format("{0:R}",dt);//Sat, 05 Nov 2005 14:23:23 GMT
Label9.Text =? string.Format("{0:s}",dt);//2005-11-05T14:23:23
Label10.Text = string.Format("{0:t}",dt);//14:23
Label11.Text = string.Format("{0:T}",dt);//14:23:23
Label12.Text = string.Format("{0:u}",dt);//2005-11-05 14:23:23Z
Label13.Text = string.Format("{0:U}",dt);//2005年11月5日 6:23:23
Label14.Text = string.Format("{0:Y}",dt);//2005年11月
Label15.Text = string.Format("{0}",dt);//2005-11-5 14:23:23?
Label16.Text = string.Format("{0:yyyyMMddHHmmssffff}",dt); //yyyymm等可以设置,比如Label16.Text = string.Format("{0:yyyyMMdd}",dt);

获得ip和mac地址


using System.Runtime.InteropServices;

[DllImport(
"Iphlpapi.dll")]
    
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
    [DllImport(
"Ws2_32.dll")]
    
private static extern Int32 inet_addr(string ip);
    
protected void Page_Load(object sender, EventArgs e)
    {
        
        
// 在此处放置用户代码以初始化页面
        try
        {
            
string userip = Request.UserHostAddress;
            
string strClientIP = Request.UserHostAddress.ToString().Trim();
            Int32 ldest 
= inet_addr(strClientIP); //目的地的ip 
            Int32 lhost = inet_addr("");   //本地服务器的ip 
            Int64 macinfo = new Int64();
            Int32 len 
= 6;
            
int res = SendARP(ldest, 0ref macinfo, ref len);
            
string mac_src = macinfo.ToString("X");
            
if (mac_src == "0")
            {
                
if (userip == "127.0.0.1")
                    Response.Write(
"正在访问Localhost!");
                
else
                    Response.Write(
"欢迎来自IP为" + userip + "的朋友!" + "<br>");
                
return;
            }

            
while (mac_src.Length < 12)
            {
                mac_src 
= mac_src.Insert(0"0");
            }

            
string mac_dest = "";

            
for (int i = 0; i < 11; i++)
            {
                
if (0 == (i % 2))
                {
                    
if (i == 10)
                    {
                        mac_dest 
= mac_dest.Insert(0, mac_src.Substring(i, 2));
                    }
                    
else
                    {
                        mac_dest 
= "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                    }
                }
            }

            Response.Write(
"欢迎来自IP为" + userip + "<br>" + ",MAC地址为" + mac_dest + "的朋友!"

             
+ "<br>");
        }
        
catch (Exception err)
        {
            Response.Write(err.Message);
        }
    }

    
private string GetClientIP()
    {
        
string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        
if (null == result || result == String.Empty)
        {
            result 
= HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        } 
if (null == result || result == String.Empty)
        {
            result 
= HttpContext.Current.Request.UserHostAddress;
        }
        
return result;
    }

调用Win32 Api函数,非托管DLL


using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace NetMeeting.API
{
  
public class Win32
  {
    [DllImport(
"user32.dll", EntryPoint = "MessageBox", ExactSpelling = false)]
    
public static extern int MessageBox(int hWnd, string text, string caption, uint type);
  }
}
//客户调用:

using System;
using NetMeeting.API;
class test
{
  
public static void Main(string[] agrs)
  {
      Win32.MessageBox(
0,"hello ,this is a c# invoke win32 api","test",2);
  }
}

生成高质量缩略图


//方法1
public static Bitmap CreateThumbnail(Bitmap source, int thumbWi, int thumbHi, bool maintainAspect)
        {
            
// return the source image if it's smaller than the designated thumbnail
            if (source.Width < thumbWi && source.Height < thumbHi) return source;

            System.Drawing.Bitmap ret 
= null;
            
try
            {
                
int wi, hi;

                wi 
= thumbWi;
                hi 
= thumbHi;

                
if (maintainAspect)
                {
                    
// maintain the aspect ratio despite the thumbnail size parameters
                    if (source.Width > source.Height)
                    {
                        wi 
= thumbWi;
                        hi 
= (int)(source.Height * ((decimal)thumbWi / source.Width));
                    }
                    
else
                    {
                        hi 
= thumbHi;
                        wi 
= (int)(source.Width * ((decimal)thumbHi / source.Height));
                    }
                }

                
// original code that creates lousy thumbnails
                
// System.Drawing.Image ret = source.GetThumbnailImage(wi,hi,null,IntPtr.Zero);
                ret = new Bitmap(wi, hi);
                
using (Graphics g = Graphics.FromImage(ret))
                {
                    g.InterpolationMode 
= System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.FillRectangle(Brushes.White, 
00, wi, hi);
                    g.DrawImage(source, 
00, wi, hi);
                }
            }
            
catch
            {
                ret 
= null;
            }

            
return ret;
        }
//调用
 using (Graphics g = Graphics.FromImage(ret))
                {
                    g.InterpolationMode 
= System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.FillRectangle(Brushes.White, 
00, wi, hi);
                    g.DrawImage(source, 
00, wi, hi);
                }

将文件保存到数据库中


//保存文件到SQL Server数据库中
    private void FileToSql(string fileName,string tableName,string fieldName)
    {
        SqlConnection cn
=new SqlConnection ();
        FileInfo fi
=new FileInfo(fileName);
        FileStream fs
=fi.OpenRead();
        
byte[] bytes=new byte[fs.Length];
        fs.Read(bytes,
0,Convert.ToInt32(fs.Length));
        SqlCommand cm
=new SqlCommand();
        cm.Connection
=cn;
        cm.CommandType
=CommandType.Text;
        
if(cn.State==0) cn.Open();
        cm.CommandText
="insert into "+tableName+"("+fieldName+") values(@file)";
        SqlParameter spFile
=new SqlParameter("@file",SqlDbType.Image);
        spFile.Value
=bytes;
        cm.Parameters.Add(spFile);
        cm.ExecuteNonQuery();
    }
//保存文件到Access数据库中
    private void FileToAccess(string fileName,string tableName,string fieldName)
    {
        OleDbConnection cn
=new OleDbConnection ();
        FileInfo fi
=new FileInfo(fileName);
        FileStream fs
=fi.OpenRead();
        
byte[] bytes=new byte[fs.Length];
        fs.Read(bytes,
0,Convert.ToInt32(fs.Length));
        OleDbCommand cm
=new OleDbCommand();
        cm.Connection
=cn;
        cm.CommandType
=CommandType.Text;
        
if(cn.State==0) cn.Open();
        cm.CommandText
="insert into "+tableName+"("+fieldName+") values(@file)";
        OleDbParameter spFile
=new OleDbParameter("@file",OleDbType.Binary);
        spFile.Value
=bytes;
        cm.Parameters.Add(spFile);
        cm.ExecuteNonQuery();
    }
    
//保存客户端文件到数据库,fl_name为上传控件
    private void FileToDataSourse(string mailid)
    {
        
string ConnStr = "";
        
string sql = "update t_mail set attachfilename=@attachfilename,attachfile=@attachfile where mailid=" + mailid;
        SqlCommand myCommand 
= new SqlCommand(sql, new SqlConnection(ConnStr));
        
string path = fl_name.PostedFile.FileName;
        
string filename = path.Substring(path.LastIndexOf(""+ 1, path.Length - path.LastIndexOf(""- 1);
        myCommand.Parameters.Add(
"@attachfilename", SqlDbType.VarChar);
        myCommand.Parameters[
"@attachfilename"].Value = filename;
        myCommand.Parameters.Add(
"@attachfile", SqlDbType.Image);
        Stream fileStream 
= fl_name.PostedFile.InputStream;
        
int intFileSize = fl_name.PostedFile.ContentLength;
        
byte[] fileContent = new byte[intFileSize];
        
int intStatus = fileStream.Read(fileContent, 0, intFileSize); //文件读取到fileContent数组中
        myCommand.Parameters["@attachfile"].Value = ((byte[])fileContent);
        fileStream.Close();
        myCommand.Connection.Open();
        myCommand.ExecuteNonQuery();
        myCommand.Connection.Close();
    }

将用户输入的字符串转换为可换行、替换Html编码、无危害数据库特殊字符、去掉首尾空白、的安全方便代码


public static string ConvertStr(string inputString)
        {
            
string retVal = inputString;
            retVal 
= retVal.Replace("&""&amp;");
            retVal 
= retVal.Replace("\"""&quot;");
            retVal = retVal.Replace("<""&lt;");
            retVal 
= retVal.Replace(">""&gt;");
            retVal 
= retVal.Replace(" ""&nbsp;");
            retVal 
= retVal.Replace("  ""&nbsp;&nbsp;");
            retVal 
= retVal.Replace("\t""&nbsp;&nbsp;");
            retVal 
= retVal.Replace("\r""<br>");
            
return retVal;
        }

        
private static string FetchURL(string strMessage)
        {
            
string strPattern = @"(?<url>(http|ftp|mms|rstp|news|https)://(?:[\w-]+\.)+[\w-]+(?:/[\w-./?%&~=]*[^.\s|,|\)|<|!])?)";
            
string strReplace = "<a href=\"${url}\" target=_blank>${url}</a>";
            
string strInput = strMessage;
            
string strResult;
            strResult 
= Regex.Replace(strInput, strPattern, strReplace);
            strPattern 
= @"(?<!http://)(?<url>www\.(?:[\w-]+\.)+[\w-]+(?:/[\w-./?%&~=]*[^.\s|,|\)|<|!])?)";
            strReplace 
= "<a href=\"http://${url}\" target=_blank>${url}</a>";
            strResult = Regex.Replace(strResult, strPattern, strReplace);
            
return strResult;
        } 

        
public string ToUrl(string inputString)
        {
            
string retVal = inputString;
            retVal 
= ConvertStr(retVal);
            retVal 
= FetchURL(retVal);
            
return retVal;
        }
 

 /// <summary>
        /// 格式化字节格式
        /// </summary>
        /// <param name="byteStr"></param>
        /// <returns></returns>
        public string FormatBytes(double bytes)
        {
            if (bytes > 1073741824)
            {
                return ((Math.Round((bytes / 1073741824) * 100) / 100).ToString() + " G");
            }
            else if (bytes > 1048576)
            {
                return ((Math.Round((bytes / 1048576) * 100) / 100).ToString() + " M");
            }
            else if (bytes > 1024)
            {
                return ((Math.Round((bytes / 1024) * 100) / 100).ToString() + " K");
            }
            else
            {
                return (bytes.ToString() + " Bytes");
            }
        }

        /// <summary>
        /// 格式化字节格式
        /// </summary>
        /// <param name="byteStr"></param>
        /// <returns></returns>
        public string FormatBytes(string byteStr)
        {
            return FormatBytes((double)TypeConverter.StrToInt(byteStr));
        }

 
ASP.NET获取服务器信息方法

if (!IsPostBack)
            {
                Label1.Text 
= "服务器名称:"+Server.MachineName;//服务器名称
                Label2.Text = "服务器IP地址:" + Request.ServerVariables["LOCAL_ADDR"];//服务器IP地址
                Label3.Text = "服务器域名:" + Request.ServerVariables["SERVER_NAME"];//服务器域名
                Label4.Text = ".NET解释引擎版本:" + ".NET CLR" + Environment.Version.Major + "." + Environment.Version.Minor + "." + Environment.Version.Build + "." + Environment.Version.Revision;//.NET解释引擎版本
                Label5.Text = "服务器操作系统版本:" + Environment.OSVersion.ToString();//服务器操作系统版本
                Label6.Text = "服务器IIS版本:" + Request.ServerVariables["SERVER_SOFTWARE"];//服务器IIS版本
                Label7.Text = "HTTP访问端口:" + Request.ServerVariables["SERVER_PORT"];//HTTP访问端口
                Label8.Text = "虚拟目录的绝对路径:" + Request.ServerVariables["APPL_RHYSICAL_PATH"];//虚拟目录的绝对路径
                Label9.Text = "执行文件的绝对路径:" + Request.ServerVariables["PATH_TRANSLATED"];//执行文件的绝对路径
                Label10.Text = "虚拟目录Session总数:" + Session.Contents.Count.ToString();//虚拟目录Session总数
                Label11.Text = "虚拟目录Application总数:" + Application.Contents.Count.ToString();//虚拟目录Application总数
                Label12.Text = "域名主机:" + Request.ServerVariables["HTTP_HOST"];//域名主机
                Label13.Text = "服务器区域语言:" + Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"];//服务器区域语言
                Label14.Text = "用户信息:" + Request.ServerVariables["HTTP_USER_AGENT"];
                Label14.Text
="CPU个数:"+Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS");//CPU个数
                Label15.Text = "CPU类型:" + Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER");//CPU类型
                Label16.Text = "进程开始时间:" + GetPrStart();//进程开始时间
                Label17.Text = "AspNet 内存占用:" + GetAspNetN();//AspNet 内存占用
                Label18.Text = "AspNet CPU时间:" + GetAspNetCpu();//AspNet CPU时间
                Label19.Text = "FSO 文本文件读写:" + Check("Scripting.FileSystemObject");//FSO 文本文件读写
                Label20.Text = "应用程序占用内存" + GetServerAppN();//应用程序占用内存
            }

ASP.NET获取客户端信息


客户端IP:Page.Request.UserHostAddress
用户信息:Page.User;
服务器电脑名称:Page.Server.MachineName
当前用户电脑名称: System.Net.Dns.GetHostName()
当前电脑名: System.Environment.MachineName
当前电脑所属网域: System.Environment.UserDomainName
当前电脑用户: System.Environment.UserName

浏览器类型:Request.Browser.Browser
浏览器标识:Request.Browser.Id
浏览器版本号:Request.Browser.Version
浏览器是不是测试版本:Request.Browser.Beta
浏览器的分辨率(像素):Request[
"width"].ToString() + "*" + Request["height"].ToString();//1280/1024

客户端的操作系统:Request.Browser.Platform
是不是win16系统:Request.Browser.Win16
是不是win32系统:Request.Browser.Win32

//透过代理取IP
string GetIp()
{
//可以透过代理服务器
string userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (userIP == null || userIP == "")
{
//没有代理服务器,如果有代理服务器获取的是代理服务器的IP
userIP = Request.ServerVariables["REMOTE_ADDR"];
}
return userIP;
}

 C#实现页面加载


protected void Page_Load(object sender, EventArgs e)
    {
        Loading();
    }

public void Loading()
    {
        HttpContext hc 
= HttpContext.Current;
        
//创建一个页面居中的div
        hc.Response.Write("<div id='loading'style='position: absolute; height: 100px; text-align: center;z-index: 9999; left: 50%; top: 50%; margin-top: -50px; margin-left: -175px;'> ");
        hc.Response.Write(
"<br />页面正在加载中,请稍候<br /><br /> ");
        hc.Response.Write(
"<table border='0' cellpadding='0' cellspacing='0' style='background-image: url(images/Progress/plan-bg.gif);text-align: center; width: 300px;'> ");
        hc.Response.Write(
"<tr><td style='height: 20px; text-align: center'><marquee direction='right' scrollamount='30' width='290px'> <img height='10' src='images/Progress/plan-wait.gif' width='270' />");
        hc.Response.Write(
"</marquee></td></tr></table></div>");
        
//hc.Response.Write("<script>mydiv.innerText = '';</script>");
        hc.Response.Write("<script type=text/javascript>");
        
//最重要是这句了,重写文档的onreadystatechange事件,判断文档是否加载完毕
        hc.Response.Write("function document.onreadystatechange()");
        hc.Response.Write(
@"{ try  
                                   {
                                    if (document.readyState == 'complete') 
                                    {
                                         delNode('loading');
                                        
                                    }
                                   }
                                 catch(e)
                                    {
                                        alert('页面加载失败');
                                    }
                                                        } 

                            function delNode(nodeId)
                            {   
                                try
                                {   
                                      var div =document.getElementById(nodeId); 
                                      if(div !==null)
                                      {
                                          div.parentNode.removeChild(div);   
                                          div=null;    
                                          CollectGarbage(); 
                                      } 
                                }
                                catch(e)
                                {   
                                   alert('删除ID为'+nodeId+'的节点出现异常');
                                }   
                            }

                            
");

        hc.Response.Write(
"</script>");
        hc.Response.Flush();
    }

 Http请求图片显示:


public Image byteArrayToImage()    
{        
WebRequest myWebRequest 
= WebRequest.Create("图片地址");        
using (WebResponse myWebResponse = myWebRequest.GetResponse())        
{            
using (Stream ReceiveStream = myWebResponse.GetResponseStream())            {                byte[] byteArrayIn = new byte[ReceiveStream.Length];                
using (MemoryStream ms = new MemoryStream(byteArrayIn))                
{       
Image.FromStream(ms);                
}            
}        
}
}

通过文件流判断文件编码:


public static System.Text.Encoding GetFileEncode(Stream stream)
        {
            BinaryReader br 
= new BinaryReader(stream, Encoding.Default);
            
byte[] bb = br.ReadBytes(3);
            br.Close();

            
//通过头的前三位判断文件的编码
            if (bb[0>= 0xFF)
            {
                
if (bb[0== 0xEF && bb[1== 0xBB && bb[2== 0xBF)
                {
                    
return Encoding.UTF8;
                }
                
else if (bb[0== 0xFE && bb[1== 0xFF)
                {
                    
return Encoding.BigEndianUnicode;
                }
                
else if (bb[0== 0xFF && bb[1== 0xFE)
                {
                    
return Encoding.Unicode;
                }
                
else
                {
                    
return Encoding.Default;
                }
            }
            
else
            {
                
return Encoding.Default;
            }
        }
posted @ 2011-12-14 13:49  火腿骑士  阅读(336)  评论(0编辑  收藏  举报