您的位置:首页 > 其它

NET开发中你可能会用到的常用方法总结

2009-08-26 21:02 609 查看
将文件转换成字符串,常用于读取网站模板



Code

/// <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文件



Code

/// <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;

}

}

取得文件扩展名



Code

/// <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];

}

替换文本中的空格和换行



Code

/// <summary>

/// 替换文本中的空格和换行

/// </summary>

public static string ReplaceSpace(string str)

{

string s = str;

s = s.Replace(" ", " ");

s = s.Replace("/n", "<BR />");

return s;

}

验证码实现方法



Code

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, 3, 3);

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();

}

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



Code

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

去掉结尾,



Code

/// <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;

}

}

}

生成任意位数的随机数



Code

/// <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();

实现文件的上传



Code

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 != 0) return 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.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;

}

}

判断输入是否为日期类型



Code

/// <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加密字符串处理



Code

/// <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(8, 16);

return output;

}

public static string MD5(string Input)

{

return MD5(Input, true);

}

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



Code

/// <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)



Code

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值



Code

/// <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 "";

}

读取配置文件的节点内容



Code

/// <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;

}

取单个字符的拼音声母



Code

/// <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 < 0xB0A1) return "*";

if (i < 0xB0C5) return "A";

if (i < 0xB2C1) return "B";

if (i < 0xB4EE) return "C";

if (i < 0xB6EA) return "D";

if (i < 0xB7A2) return "E";

if (i < 0xB8C1) return "F";

if (i < 0xB9FE) return "G";

if (i < 0xBBF7) return "H";

if (i < 0xBFA6) return "G";

if (i < 0xC0AC) return "K";

if (i < 0xC2E8) return "L";

if (i < 0xC4C3) return "M";

if (i < 0xC5B6) return "N";

if (i < 0xC5BE) return "O";

if (i < 0xC6DA) return "P";

if (i < 0xC8BB) return "Q";

if (i < 0xC8F6) return "R";

if (i < 0xCBFA) return "S";

if (i < 0xCDDA) return "T";

if (i < 0xCEF4) return "W";

if (i < 0xD1B9) return "X";

if (i < 0xD4D1) return "Y";

if (i < 0xD7FA) return "Z";

return "*";

}

变量.ToString()



Code

//字符型转换 转为字符串

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%

时间的处理



Code

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地址



Code

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, 0, ref 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



Code

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

  }

}

生成高质量缩略图



Code

//方法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, 0, 0, wi, hi);

g.DrawImage(source, 0, 0, wi, hi);

}

}

catch

{

ret = null;

}

return ret;

}

//调用

using (Graphics g = Graphics.FromImage(ret))

{

g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

g.FillRectangle(Brushes.White, 0, 0, wi, hi);

g.DrawImage(source, 0, 0, wi, hi);

}

将文件保存到数据库中



Code

//保存文件到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编码、无危害数据库特殊字符、去掉首尾空白、的安全方便代码



Code

public static string ConvertStr(string inputString)

{

string retVal = inputString;

retVal = retVal.Replace("&", "&");

retVal = retVal.Replace("/"", """);

retVal = retVal.Replace("<", "<");

retVal = retVal.Replace(">", ">");

retVal = retVal.Replace(" ", " ");

retVal = retVal.Replace(" ", "  ");

retVal = retVal.Replace("/t", "  ");

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

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

strResult = Regex.Replace(strResult, strPattern, strReplace);

return strResult;

}

public string ToUrl(string inputString)

{

string retVal = inputString;

retVal = ConvertStr(retVal);

retVal = FetchURL(retVal);

return retVal;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: