知识大全 ASP.NET(C#)
Posted 文件
篇首语:丈夫欲遂平生志,一载寒窗一举汤。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 ASP.NET(C#)相关的知识,希望对你有一定的参考价值。
ASP.NET(C#) 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!
一个生成不重复随机数的方法 //生成不重复随机数算法 private int GetRandomNum(int i int length int up int down) int iFirst= ; Random ro=new Random(i*length*unchecked((int)DateTime Now Ticks)) iFirst=ro Next(up down) return iFirst; 发表于 @ 年 月 日 : PM | 评论 ( ) ASP NET多文件上传方法 前台代码 <script language= Javascript > function addFile() var str = <INPUT type= file size= NAME= File ><br> document getElementById( MyFile ) insertAdjacentHTML( beforeEnd str) </script> <form id= form method= post runat= server enctype= multipart/form data > <div align= center > <h >多文件上传</h > <P id= MyFile ><INPUT type= file size= NAME= File ><br></P> <P> <input type= button value= 增加(Add) onclick= addFile() > <input onclick= this form reset() type= button value= 重置(ReSet) > <asp:Button Runat= server Text= 开始上传 ID= UploadButton > </asp:Button> </P> <P> <asp:Label id= strStatus runat= server Font Names= 宋体 Font Bold= True Font Size= pt Width= px BorderStyle= None BorderColor= White ></asp:Label> </P> </div> </form> 后台代码 protected System Web UI WebControls Button UploadButton; protected System Web UI WebControls Label strStatus; private void Page_Load(object sender System EventArgs e) /// 在此处放置用户代码以初始化页面 if (this IsPostBack) this SaveImages() private Boolean SaveImages() /// 遍历File表单元素 HttpFileCollection files = HttpContext Current Request Files; /// 状态信息 System Text StringBuilder strMsg = new System Text StringBuilder() strMsg Append( 上传的文件分别是 <hr color=red> ) try for(int iFile = ; iFile < files Count; iFile++) /// 检查文件扩展名字 HttpPostedFile postedFile = files[iFile]; string fileName fileExtension file_id; //取出精确到毫秒的时间做文件的名称 int year = System DateTime Now Year; int month = System DateTime Now Month; int day = System DateTime Now Day; int hour = System DateTime Now Hour; int minute = System DateTime Now Minute; int second = System DateTime Now Second; int millisecond = System DateTime Now Millisecond; string my_file_id = year ToString() + month ToString() + day ToString() + hour ToString() + minute ToString() + second ToString() + millisecond ToString()+iFile ToString() fileName = System IO Path GetFileName(postedFile FileName) fileExtension = System IO Path GetExtension(fileName) file_id = my_file_id+fileExtension; if (fileName != ) fileExtension = System IO Path GetExtension(fileName) strMsg Append( 上传的文件类型 + postedFile ContentType ToString() + <br> ) strMsg Append( 客户端文件地址 + postedFile FileName + <br> ) strMsg Append( 上传文件的文件名 + file_id + <br> ) strMsg Append( 上传文件的扩展名 + fileExtension + <br><hr> ) postedFile SaveAs(System Web HttpContext Current Request MapPath( images/ ) + file_id) strStatus Text = strMsg ToString() return true; catch(System Exception Ex) strStatus Text = Ex Message; return false; 发表于 @ 年 月 日 : PM | 评论 ( ) 邮件系统使用的上传附件方法 前台HTML代码 <form id= mail method= post runat= server > <table border= cellpadding= cellspacing= bordercolor= # width= % id= AutoNumber height= > <tr> <td width= % height= ><INPUT id= myFile type= file size= name= myFile runat= server > <asp:button id= Upload runat= server Text= 上传附件 ></asp:button></td> </tr> <tr> <td width= % height= > 共计 <asp:textbox id= P_size runat= server Width= px ></asp:textbox>KB <asp:dropdownlist id= dlistBound runat= server ></asp:dropdownlist> <asp:button id= btnDel runat= server Text= 删除附件 ></asp:button></td> </tr> </table> </form> 后台CS代码 public class Upload_Mail : System Web UI Page protected System Web UI WebControls Button Upload; protected System Web UI WebControls DropDownList dlistBound; protected System Web UI WebControls TextBox P_size; protected System Web UI WebControls Button btnDel; protected System Web UI HtmlControls HtmlInputFile myFile; private void Page_Load(object sender System EventArgs e) if (!IsPostBack) //没有附件的状态 dlistBound Items Clear() ArrayList arr = new ArrayList() arr Add( 没有附件 ) dlistBound DataSource = arr ; dlistBound DataBind() P_size Text = ; private void Upload_Click(object sender System EventArgs e) if(myFile PostedFile !=null) HttpFileCollection files = HttpContext Current Request Files; HttpPostedFile postedFile = files[ ]; string fileName = System IO Path GetFileName(postedFile FileName) string path = Request PhysicalApplicationPath+@ UploadMail\\ + fileName; postedFile SaveAs(path) //数组对上存附件进行实时绑定 if((string)Session[ udMail ]==null) Session[ udMail ] = fileName; else Session[ udMail ] = (string)Session[ udMail ]+ | +fileName; string[] udMail = Session[ udMail ] ToString() Split( | ) ArrayList list = new ArrayList(udMail) list Reverse() udMail=(string[])list ToArray(typeof(string)) dlistBound Items Clear() long dirsize= ; for(int i = ;i<udMail Length;i++) string IndexItem = udMail[i]; string VauleItem = Request PhysicalApplicationPath+@ UploadMail\\ +udMail[i]; dlistBound Items Add(new ListItem(IndexItem VauleItem)) System IO FileInfo mysize = new System IO FileInfo(@VauleItem) dirsize += System Convert ToInt (mysize Length/ )+ ; P_size Text = dirsize ToString() private void btnDel_Click(object sender System EventArgs e) string trueDelfile = dlistBound SelectedValue ToString() string Delfile = dlistBound SelectedItem ToString() usageIO DeletePath(trueDelfile) if(Session[ udMail ] != null) int index = Session[ udMail ] ToString() IndexOf( | ) if(index == ) Session[ udMail ] = null; dlistBound Items Clear() dlistBound Items Add( 没有附件 ) P_size Text = ; else string[] udMail = Session[ udMail ] ToString() Split( | ) ArrayList values = new ArrayList(udMail) values Remove(Delfile) string s = null; for(int i= ;i<values Count;i++) if(values Count!= ) s += values[i] ToString()+ | ; if(s!= ||s!=null) s = s TrimEnd( | ) Session[ udMail ] = s; string[] uMail = Session[ udMail ] ToString() Split( | ) ArrayList list = new ArrayList(uMail) list Reverse() uMail=(string[])list ToArray(typeof(string)) dlistBound Items Clear() long dirsize= ; for(int i = ;i<uMail Length;i++) string IndexItem = uMail[i]; string VauleItem = Request PhysicalApplicationPath+@ UploadMail\\ +uMail[i]; dlistBound Items Add(new ListItem(IndexItem VauleItem)) System IO FileInfo mysize = new System IO FileInfo(@VauleItem) dirsize += System Convert ToInt (mysize Length/ )+ ; P_size Text = dirsize ToString() Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码 override protected void OnInit(EventArgs e) // // CODEGEN: 该调用是 ASP NET Web 窗体设计器所必需的 // InitializeComponent() base OnInit(e) /**//// <summary> /// 设计器支持所需的方法 不要使用代码编辑器修改 /// 此方法的内容 /// </summary> private void InitializeComponent() this Upload Click += new System EventHandler(this Upload_Click) this btnDel Click += new System EventHandler(this btnDel_Click) this Load += new System EventHandler(this Page_Load) #endregion 发表于 @ 年 月 日 : PM | 评论 ( ) 上传图片并且生成可以控制大小图片清晰度的方法 private void Upload_Click(object sender System EventArgs e) if(myFile PostedFile !=null) // 检查文件扩展名字 HttpFileCollection files = HttpContext Current Request Files; HttpPostedFile postedFile = files[ ]; string fileName fileExtension file_id file_path; //取出精确到毫秒的时间做文件的名称 int year = System DateTime Now Year; int month = System DateTime Now Month; int day = System DateTime Now Day; int hour = System DateTime Now Hour; int minute = System DateTime Now Minute; int second = System DateTime Now Second; int millisecond = System DateTime Now Millisecond; string my_file_id = year ToString() + month ToString() + day ToString() + hour ToString() + minute ToString() + second ToString() + millisecond ToString() //获得文件类型 fileName = System IO Path GetFileName(postedFile FileName) fileExtension = System IO Path GetExtension(fileName) //重新命名文件 防止重复 file_id = topnews_ +my_file_id+fileExtension; file_path = images/article_images/ +file_id; //文件上传到服务器的根目录 postedFile SaveAs(Request PhysicalApplicationPath+@ images\\article_images\\ + file_id) //处理图片大小 int width height level; width= ; height= ; level= ;//从 GetThumbnailImage(width height level file_id) //生成缩略图函数 public void GetThumbnailImage(int width int height int level string file_id) string newfile= Request PhysicalApplicationPath+ images/article_images/ + top_ + file_id; System Drawing Image oldimage = System Drawing Image FromFile(Request PhysicalApplicationPath+ images/article_images/ + file_id) System Drawing Image thumbnailImage = oldimage GetThumbnailImage(width height new System Drawing Image GetThumbnailImageAbort(ThumbnailCallback) IntPtr Zero) Bitmap output=new Bitmap(thumbnailImage) //处理JPG质量的函数 ImageCodecInfo[] codecs=ImageCodecInfo GetImageEncoders() ImageCodecInfo ici=null; foreach(ImageCodecInfo codec in codecs)if(codec MimeType== image/jpeg )ici=codec; EncoderParameters ep=new EncoderParameters() ep Param[ ]=new EncoderParameter(Encoder Quality (long)level) output Save(newfile ici ep) //释放所有使用对象 ep Dispose() output Dispose() oldimage Dispose() thumbnailImage Dispose() //删除源图片 string file_path = images/article_images/ + top_ +file_id; usageIO DeletePath(Request PhysicalApplicationPath+ images/article_images/ + file_id) Response Write( <script >parent Form A_Simg value = +file_path+ ;location replace( Upload_Img aspx )</script> ) bool ThumbnailCallback() return false; 发表于 @ 年 月 日 : PM | 评论 ( ) 生成高清晰度的缩略图[方法 ] public void pic_zero(string sourcepath string aimpath int scale) string originalFilename =sourcepath; //生成的高质量图片名称 string strGoodFile =aimpath; //从文件取得图片对象 System Drawing Image image = System Drawing Image FromFile(originalFilename) int iImgWidth = image Width; int iImgHeight = image Height; int iScale = (iImgWidth / scale)>(iImgHeight/scale) ? (iImgWidth / scale) : (iImgHeight / scale) //取得图片大小 System Drawing Size size = new Size(image Width / iScale image Height / iScale) //新建一个bmp图片 System Drawing Image bitmap = new System Drawing Bitmap(size Width size Height) //新建一个画板 System Drawing Graphics g = System Drawing Graphics FromImage(bitmap) //设置高质量插值法 g InterpolationMode = System Drawing Drawing D InterpolationMode High; //设置高质量 低速度呈现平滑程度 g SmoothingMode = System Drawing Drawing D SmoothingMode HighQuality; //清空一下画布 g Clear(Color Blue) //在指定位置画图 g DrawImage(image new System Drawing Rectangle( bitmap Width bitmap Height) new System Drawing Rectangle( image Width image Height) System Drawing GraphicsUnit Pixel) //保存高清晰度的缩略图 bitmap Save(strGoodFile System Drawing Imaging ImageFormat Jpeg) g Dispose() 发表于 @ 年 月 日 : PM | 评论 ( ) 比较完美的图片验证码 需要引用的名字空间 using System IO; using System Drawing Imaging; using System Drawing Drawing D; public class ValidationCodeImg : System Web UI Page private void Page_Load(object sender System EventArgs e) this CreateCheckCodeImage(GenerateCheckCode()) private string GenerateCheckCode() int number; char code; string checkCode = String Empty; System Random random = new Random() for(int i= ; i< ; i++) number = random Next() if(number % == ) code = (char)( + (char)(number % )) else code = (char)( + (char)(number % )) checkCode += code ToString() Response Cookies Add(new HttpCookie( CheckCode checkCode)) return checkCode; private void CreateCheckCodeImage(string checkCode) if(checkCode == null || checkCode Trim() == String Empty) return; System Drawing Bitmap image = new System Drawing Bitmap((int)Math Ceiling((checkCode Length * )) ) Graphics g = Graphics FromImage(image) try //生成随机生成器 Random random = new Random() //清空图片背景色 g Clear(Color White) //画图片的背景噪音线 for(int i= ; i< ; i++) int x = random Next(image Width) int x = random Next(image Width) int y = random Next(image Height) int y = random Next(image Height) g DrawLine(new Pen(Color Silver) x y x y ) Font font = new System Drawing Font( Tahoma (System Drawing FontStyle Bold | System Drawing FontStyle Italic)) System Drawing Drawing D LinearGradientBrush brush = new System Drawing Drawing D LinearGradientBrush(new Rectangle( image Width image Height) Color Black Color Black f true) g DrawString(checkCode font brush ) //画图片的前景噪音点 for(int i= ; i< ; i++) int x = random Next(image Width) int y = random Next(image Height) image SetPixel(x y Color FromArgb(random Next())) //画图片的边框线 g DrawRectangle(new Pen(Color Silver) image Width image Height ) System IO MemoryStream ms = new System IO MemoryStream() image Save(ms System Drawing Imaging ImageFormat Gif) Response ClearContent() Response ContentType = image/Gif ; Response BinaryWrite(ms ToArray()) finally g Dispose() image Dispose() 发表于 @ 年 月 日 : PM | 评论 ( ) IE订单的打印处理办法 在一个商城项目应用中我需要把客户在网上下的订单使用IE打印出来 首先必须控制订单不能出现IE的页眉页脚(需要使用ScriptX) <OBJECT id= factory codeBase= classid= clsid: ed eb d b f fdd viewastext> </OBJECT> <SCRIPT defer> function println() factory printing header = factory printing footer = factory printing Print(true) factory printing leftMargin = factory printing topMargin = factory printing rightMargin = factory printing bottomMargin = window print() </SCRIPT> 然后主要是控制订单数据输出用什么办法显示出来 为了灵活的控制输出效果 我这里使用的是循环读入数据(定购的商品)的办法(下面的代码是我使用的) public string myOrder(string B_No) nn Open() string strFirstMenu =null; string strSql = select Items_Type Items_Name Items_Unit Items_Count Items_Price from [OrderItems] where Order_No = +B_No+ order by ID desc ; SqlDataAdapter da = new SqlDataAdapter(strSql nn) DataSet ds = new DataSet() da Fill(ds myOrder ) int count = ds Tables[ ] Rows Count; string Items_Type Items_Name Items_Price Items_Count Items_Unit Items_TotalPrice; Double Items_AllTotalPrice = ; int Items_TotalCount = ; string begin = <table id =\\ inc\\ style=\\ BORDER COLLAPSE: collapse\\ borderColor=\\ # \\ height=\\ \\ cellSpacing=\\ \\ cellPadding=\\ \\ width=\\ %\\ border=\\ \\ ><tr><td align=\\ center\\ width=\\ %\\ height=\\ \\ >商品编号</td><td align=\\ center\\ width=\\ %\\ height=\\ \\ >商品名称</td><td align=\\ center\\ width=\\ %\\ height=\\ \\ >单位</td><td align=\\ center\\ width=\\ %\\ height=\\ \\ >数量</td><td align=\\ center\\ width=\\ %\\ height=\\ \\ >单价(元)</td><td align=\\ center\\ width=\\ %\\ height=\\ \\ >金额(元)</td></tr> ; for(int rb = ; rb < count;rb++) Items_Type = ds Tables[ ] Rows[rb][ ] ToString() Items_Name = ds Tables[ ] Rows[rb][ ] ToString() Items_Unit = ds Tables[ ] Rows[rb][ ] ToString() Items_Count = ds Tables[ ] Rows[rb][ ] ToString() Items_Price = Double Parse(ds Tables[ ] Rows[rb][ ] ToString()) ToString( ) Items_TotalPrice = (Double Parse(Items_Price)*Double Parse(Items_Count)) ToString( ) Items_AllTotalPrice += Double Parse(Items_TotalPrice) Items_TotalCount += Int Parse(Items_Count) strFirstMenu += <tr><td width=\\ %\\ height=\\ \\ > +Items_Type+ </td><td width=\\ %\\ height=\\ \\ > +Items_Name+ </td><td width=\\ %\\ height=\\ \\ > +Items_Unit+ </td><td width=\\ %\\ height=\\ \\ > +Items_Count+ </td><td width=\\ %\\ height=\\ \\ > +Items_Price+ </td><td width=\\ %\\ height=\\ \\ > +Items_TotalPrice+ </td></tr> ; string FirstMenu = begin+strFirstMenu+ </table> ; nn Close() return FirstMenu; 发表于 @ 年 月 日 : PM | 评论 ( ) URL传输参数加密解密 最近做一个论坛入口时要实现帐号和密码不在IE地址栏出现而做的 index aspx cs (加密处理) Byte[] Iv = ; Byte[] byKey = ; public string Encrypt(string strText) try DESCryptoServiceProvider des = new DESCryptoServiceProvider() Byte[] inputByteArray = Encoding UTF GetBytes(strText) MemoryStream ms = new MemoryStream() CryptoStream cs = new CryptoStream(ms des CreateEncryptor(byKey Iv ) CryptoStreamMode Write) cs Write(inputByteArray inputByteArray Length) cs FlushFinalBlock() return Convert ToBase String(ms ToArray()) catch(Exception ex) return ex Message; private void btnLogin_Click(object sender System Web UI ImageClickEventArgs e) DateTime nowTime = DateTime Now; string postUser = txtUser Text ToString() string postPass = txtPassword Text ToString() Response Redirect( Login aspx?clubID= +Encrypt(postUser+ +postPass+ +nowTime ToString())) login aspx cs (解密处理) //随机选 个字节既为密钥也为初始向量 Byte[] byKey = ; Byte[] Iv = ; public string Decrypt(string strText) Byte[] inputByteArray = new byte[strText Length]; try DESCryptoServiceProvider des = new DESCryptoServiceProvider() inputByteArray = Convert FromBase String(strText) MemoryStream ms = new MemoryStream() CryptoStream cs = new CryptoStream(ms des CreateDecryptor(byKey Iv ) CryptoStreamMode Write) cs Write(inputByteArray inputByteArray Length) cs FlushFinalBlock() System Text Encoding encoding = System Text Encoding UTF ; return encoding GetString(ms ToArray()) catch(Exception ex) return ex Message; private void Page_Load(object sender System EventArgs e) if(Request Params[ clubID ]!=null) string originalValue = Request Params[ clubID ]; originalValue = originalValue Replace( + ) //+号通过url传递变成了空格 string decryptResult = Decrypt(originalValue) //DecryptString(string)解密字符串 string delimStr = ; char[] delimiterArray = delimStr ToCharArray() string [] userInfoArray = null; userInfoArray = decryptResult Split(delimiterArray) string userName = userInfoArray[ ]; User userToLogin = new User() userToLogin Username = userInfoArray[ ]; userToLogin Password = userInfoArray[ ]; …… cha138/Article/program/net/201311/13020相关参考
ASP.net(C#)批量上传图片 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧! 因本网站上传图
ASP.NET学习笔记之c#必会 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧! &nbs
asp.net(C#)套用模板操作Excel 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧! 当需
Asp.net(C#)实现验证码功能两法 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!
ASP.Net之C#中的异常处理 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧! 基础知识 程序
ASP.NET(c#)实现中英文域名查询 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧! 引言
ASP.Net之C#中的异常处理[2] 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧! &
ASP.Net之C#中的异常处理[1] 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧! &
在Asp.net用C#建立动态Excel 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧! 在中建立
ASP.NET项目开发指南:C#操作XML(2) 以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!