asp.net基于windows服务实现定时发送邮件的方法
本文实例讲述了asp.net基于windows服务实现定时发送邮件的方法。分享给大家供大家参考,具体如下:
//定义组件 privateSystem.Timers.Timertime; publicintnowhour; publicintminutes; publicstringsendTime; publicThreadth; publicstringisOpen;//是否启用定时发送 publicstringstrToEUser; publicstaticintindex=-1; publicstaticArrayListmulitaddress; //服务开始 protectedoverridevoidOnStart(string[]args) { time=newSystem.Timers.Timer(); time.Enabled=true; time.AutoReset=true; //定时执行方法 time.Elapsed+=newSystem.Timers.ElapsedEventHandler(time_Elapsed); UserEmailtoUser=newUserEmail(); mulitaddress=GetMailAdressName(); //LogHelper.SaveNote("当前索引的值"+index.ToString()); Thread.Sleep(2000); time.Start(); } publicclassLogHelper { publicstaticvoidSaveNote(stringnote) { FileStreamstream=newFileStream(GetLogDirectory("Common")+DateTime.Now.ToString("yyyy-MM-dd")+".txt",FileMode.Append,FileAccess.Write,FileShare.Delete|FileShare.ReadWrite); StreamWriterwriter=newStreamWriter(stream,Encoding.UTF8); writer.WriteLine("================================================================"); writer.WriteLine(string.Format("Note:/t{0}",note)); writer.WriteLine(string.Format("DateTime:/t{0}/r/n/r/n",DateTime.Now.ToString())); stream.Flush(); writer.Close(); stream.Close(); stream.Dispose(); writer.Dispose(); } publicstaticvoidSaveNote(stringnote,stringtxtname) { FileStreamstream=newFileStream(GetLogDirectory(txtname)+DateTime.Now.ToString("yyyy-MM-dd")+".txt",FileMode.Append,FileAccess.Write,FileShare.Delete|FileShare.ReadWrite); StreamWriterwriter=newStreamWriter(stream,Encoding.GetEncoding("gb2312")); writer.WriteLine("================================================================"); writer.WriteLine(string.Format("Note:/t{0}",note)); writer.WriteLine(string.Format("DateTime:/t{0}/r/n/r/n",DateTime.Now.ToString("yyyyMMddHHmmss"))); stream.Flush(); writer.Close(); stream.Close(); stream.Dispose(); writer.Dispose(); } publicstaticvoidSaveException(Exceptione) { SaveException(e,string.Empty); } publicstaticvoidSaveException(Exceptione,stringmemo) { FileStreamstream=newFileStream(GetLogDirectory("Common")+DateTime.Now.ToString("yyyy-MM-dd")+".txt",FileMode.Append,FileAccess.Write,FileShare.Delete|FileShare.ReadWrite); StreamWriterwriter=newStreamWriter(stream); writer.WriteLine("================================================================"); writer.WriteLine(string.Format("Memo:/t{0}",memo)); writer.WriteLine(string.Format("DateTime:/t{0}",DateTime.Now.ToShortTimeString())); writer.WriteLine(string.Format("Message:/t{0}",e.Message)); writer.WriteLine(string.Format("StackTrace:/r/n----------/r/n{0}/r/n----------/r/n/r/n/r/n",e.StackTrace)); stream.Flush(); writer.Close(); stream.Close(); stream.Dispose(); writer.Dispose(); } publicstaticstringGetLogDirectory(stringcategory) { stringbaseDirectory=string.Empty; if((HttpContext.Current!=null)&&(HttpContext.Current.Server!=null)) { baseDirectory=HttpContext.Current.Server.MapPath("~"); } else { baseDirectory=AppDomain.CurrentDomain.BaseDirectory; } if((baseDirectory[baseDirectory.Length-1]!='/')&&(baseDirectory[baseDirectory.Length-1]!='//')) { baseDirectory=baseDirectory+@"/"; } baseDirectory=string.Format(@"{0}Log/{1}/",baseDirectory,category); if(!Directory.Exists(baseDirectory)) { Directory.CreateDirectory(baseDirectory); } returnbaseDirectory; } } voidtime_Elapsed(objectsender,System.Timers.ElapsedEventArgse) { try { if(mulitaddress!=null) { LogHelper.SaveNote("进入time_Elapsed"); //获取定时发送时间 sendTime=Convert.ToString(GetConfigValue("sendTime")); LogHelper.SaveNote("sendTime"+sendTime); //是否开启定时发送功能 isOpen=GetConfigValue("isOpen"); intsleeptime=Convert.ToInt32(GetConfigValue("SleepTime")); intstoptime=Convert.ToInt32(GetConfigValue("stoptime")); //LogHelper.SaveNote("数组长度"+mulitaddress.Count); //LogHelper.SaveNote("是否开启定时发送功能"+isOpen+"定时时间"+sendTime+"定时小时数:"+Convert.ToInt32(sendTime.Split(newchar[]{':'})[0])+"定时分钟数:"+Convert.ToInt32(sendTime.Split(newchar[]{':'})[1])); if(isOpen=="true") { //现在时间小时 nowhour=Convert.ToInt32(DateTime.Now.Hour.ToString());//10 //现在分钟 minutes=Convert.ToInt32(DateTime.Now.Minute.ToString());//5 //获取发送小时 intsendhour=Convert.ToInt32(sendTime.Split(newchar[]{':'})[0]); //获取发送的分钟 intsendMinute=Convert.ToInt32(sendTime.Split(newchar[]{':'})[1]); LogHelper.SaveNote("进入定时发送邮件服务!定时小时为:"+sendhour.ToString()+"定时分钟为:"+sendMinute.ToString()+"现在小时为:"+nowhour.ToString()+"现在定时的分钟为:"+minutes.ToString()); LogHelper.SaveNote("当前索引的值"+index.ToString()); if(nowhour==stoptime) { LogHelper.SaveNote("停止时间点到了邮件停止发送!!!"); index=-1; } else { //如果和当前的时间小时相等则定时发送邮件 if((Convert.ToDateTime(DateTime.Now.ToShortTimeString())>=Convert.ToDateTime(sendTime))&&index<mulitaddress.Count) { index++; if(index<mulitaddress.Count) { SendEmail(((UserEmail)mulitaddress[index])); } else { LogHelper.SaveNote("发送完毕当前的索引值为"+index.ToString()); } } } } else { //LogHelper.SaveNote("当前索引的值"+index.ToString()); index++; if(index<mulitaddress.Count) { SendEmail(((UserEmail)mulitaddress[index])); } else { LogHelper.SaveNote("发送完毕时间停止"); time.Enabled=false; time.Stop(); } } Thread.Sleep(sleeptime); } else LogHelper.SaveNote("mulitaddress=null"); } catch(Exceptionex) { LogHelper.SaveNote(ex.ToString()); } } publicArrayListGetMailAdressName() { ArrayListlist=newArrayList(); stringstrSQL="selectb.mailAddress,a.mailtemplate,a.titlefromtg_productasainnerjointg_mailOrderasbona.ccode=b.ccodewherea.createtime=(selectmax(createtime)fromtg_product)"; SqlDataReaderdr=SqlHelper.ExecuteReader(CommandType.Text,strSQL,null); if(dr.HasRows) { while(dr.Read()) { UserEmailemail=newUserEmail(); email.Mailaddres=dr["mailAddress"].ToString(); email.Title=dr["title"].ToString(); email.Contents=dr["mailtemplate"].ToString(); list.Add(email); } } returnlist; } ///<summary> ///定义用户邮件标题内容Email地址 ///</summary> publicclassUserEmail{ privatestringtitle; privatestringcontents; publicstringContents { get{returncontents;} set{contents=value;} } privatestringmailaddres; publicstringMailaddres { get{returnmailaddres;} set{mailaddres=value;} } publicstringTitle{ get{returntitle;} set{title=value;} } } #region发送邮件 ///<summary> ///发送邮件 ///</summary> publicvoidSendEmail(UserEmailuser) { try { LogHelper.SaveNote("进入SendEmail!!!"); //邮件服务器 stringsmtpserver=GetConfigValue("smtpserver"); //发件人的邮箱名称 stringemailuserName=GetConfigValue("emailuserName"); //发件人的邮箱密码 stringemailuserpwd=GetConfigValue("emailuserpwd"); //邮箱地址 stringemailfrom=GetConfigValue("emailfrom"); intport=Convert.ToInt32(GetConfigValue("serverPort")); boolf=true; //是否经过SSL加密 stringisSSL=GetConfigValue("SSL"); if(isSSL=="true") { f=true; } else { f=false; } LogHelper.SaveNote("发件人的邮箱名称"+emailuserName+"邮件地址(emailFrom)"+emailfrom+"收件人"+user.Mailaddres); SendEmailToUser(smtpserver,port,f,user.Mailaddres,null,emailuserName,emailuserpwd,emailfrom,user.Title,user.Contents); LogHelper.SaveNote("SendMailSuccess"); } //获取异常信息 catch(Exceptionerror) { //写入异常信息 using(StreamWritersw=newStreamWriter("F://MailErrorlog.txt",true,System.Text.Encoding.UTF8)) { sw.WriteLine(DateTime.Now.ToString()+":"); sw.WriteLine("Exception异常信息如下................."); sw.WriteLine(error.ToString()); sw.WriteLine("---------------------------------------------"); sw.Close(); } } } #endregion #region利用.Net自带类(SmtpClient)发送邮件 ///<summary> ///利用.Net自带类(SmtpClient)发送邮件 ///</summary> ///<paramname="stmpserver">邮件服务器</param> ///<paramname="username">用户名(邮箱名称)</param> ///<paramname="pwd">密码</param> ///<paramname="f">是否经过SSL加密</param> ///<paramname="port">邮件服务器端口(没有加密一般都是25)</param> ///<paramname="strfrom">发件人</param> ///<paramname="strto">收件人</param> ///<paramname="subject">主题</param> ///<paramname="body">内容</param> ///<paramname="Mulitaddress">发送多人收件人的邮箱地址以逗号隔开</param> ///<paramname="attachmentName">发送的附件名称没有附件则为nullor""</param> publicvoidSendEmailToUser(stringstmpserver,intport,boolf,stringMulitaddress,stringattachmentName,stringusername,stringpwd,stringstrfrom,stringsubject,stringbody) { stringErrorLog=GetConfigValue("ErrorLog"); SmtpClientsmtp=newSmtpClient(); //发送邮件的方式 smtp.DeliveryMethod=SmtpDeliveryMethod.Network; //指定邮件服务器 smtp.Host=stmpserver; //GmailQQstmpssl加密使用的端口 smtp.Port=port; smtp.EnableSsl=f;;//true经过ssl加密 //验证发件人的身份用户名(邮件地址和密码) smtp.Credentials=newSystem.Net.NetworkCredential(username,pwd); //初始化信息(来自接收人) MailMessage_mailmessage=newMailMessage(); //_mailmessage.To=strto; //发送多个人接收人邮件地址以,隔开 _mailmessage.From=newMailAddress(strfrom); _mailmessage.To.Add(Mulitaddress); //如果发送失败,SMTP服务器将发送失败邮件通知 _mailmessage.DeliveryNotificationOptions=DeliveryNotificationOptions.OnFailure; //优先级 _mailmessage.Priority=MailPriority.High; //发送主题 _mailmessage.Subject=subject; //有附件则添加附件 if(!string.IsNullOrEmpty(attachmentName)) { System.Net.Mail.Attachmentattch=newSystem.Net.Mail.Attachment(attachmentName); _mailmessage.Attachments.Add(attch); } //邮件主题编码 _mailmessage.SubjectEncoding=System.Text.Encoding.UTF8; //指定发送的格式(Html) _mailmessage.IsBodyHtml=true; //指定发送邮件的编码 _mailmessage.BodyEncoding=System.Text.Encoding.UTF8; //指定邮件内容 _mailmessage.Body=body; //发送邮件 try { smtp.Send(_mailmessage); } catch(Exceptionex) { using(StreamWriterwriter=newStreamWriter(ErrorLog+"://MailErrorlog.txt",true,System.Text.Encoding.UTF8)) { writer.WriteLine("---------------------------------------------"); writer.WriteLine("SendEmail方法发送邮件错误日志................"); writer.WriteLine(ex.ToString()); writer.Flush(); writer.Close(); } } } #endregion #region获取邮件配置节点的值 ///<summary> ///加载相应配置文件并按节点名称获取对应的值 ///</summary> ///<paramname="target">当前节点的名称</param> ///<returns>返回当前节点名称所对应的值</returns> publicstringGetConfigValue(stringtarget) { stringconfigpath=System.Windows.Forms.Application.StartupPath.ToString()+"/Email.config"; returnGetConfigValue(configpath,target); } ///<summary> ///根据节点名称获取配置文件对应的值(邮件配置信息) ///</summary> ///<paramname="configpath">配置文件路径</param> ///<paramname="target">要获取配置节点的名称</param> ///<returns>返回当前节点名称所对应的值</returns> publicstringGetConfigValue(stringconfigpath,stringtarget) { XmlDocumentdoc=newXmlDocument(); //加载文件路径s doc.Load(configpath); //获取当前节点的根节点 XmlElementroot=doc.DocumentElement; //获取当前节点下所有匹配子节点元素 XmlNodeListxmlnode=root.GetElementsByTagName(target); //返回值 returnxmlnode[0].InnerXml; } #endregion //服务结束 protectedoverridevoidOnStop() { time.Enabled=false; }
Email.Config如下:
<?xmlversion="1.0"encoding="utf-8"?> <Emailconfig> <!--邮件服务器地址Gmailstmp.gmail.com--> <smtpserver>*****</smtpserver> <!--邮箱用户名--> <emailuserName>***</emailuserName> <!--邮箱密码--> <emailuserpwd>****</emailuserpwd> <!--邮箱地址--> <emailfrom>*****</emailfrom> <!--是否启用定时发送邮件功能--> <isOpen>true</isOpen> <!--前提下isOpen为true定在每天某个时间点发送邮件--> <sendTime>8:53</sendTime> <!--是否经过SSL加密--> <SSL>false</SSL> <!--GmailsmtpSSL加密(Gmail:587)服务器端口(没有加密(SSL配置为false)一般都是25 (163,qq))--> <serverPort>25</serverPort> <!--线程睡眠时间--> <SleepTime>1000</SleepTime> <!--定停发送时间--> <stoptime>0</stoptime> <!--发送邮件错误日志路径盘根目录--> <ErrorLog>E</ErrorLog> <!--定义数据库连接字符串--> <Connstr></Connstr> </Emailconfig>
SQLHelper如下:
#region数据库操作类的封装 publicabstractclassSqlHelper { //Databaseconnectionstrings publicstaticreadonlystringConnectionStringLocalTransaction=Connstr; //Hashtabletostorecachedparameters privatestaticHashtableparmCache=Hashtable.Synchronized(newHashtable()); /*返回数据库连接*/ publicstaticSqlConnectiongetConnection() { SqlConnectionc=newSqlConnection(ConnectionStringLocalTransaction); returnc; } ///<summary> ///ExecuteaSqlCommandthatreturnsaresultsetagainstthedatabasespecifiedintheconnectionstring ///usingtheprovidedparameters. ///</summary> ///<remarks> ///e.g.: ///SqlDataReaderr=ExecuteReader(connString,CommandType.StoredProcedure,"PublishOrders",newSqlParameter("@prodid",24)); ///</remarks> ///<paramname="connectionString">avalidconnectionstringforaSqlConnection</param> ///<paramname="commandType">theCommandType(storedprocedure,text,etc.)</param> ///<paramname="commandText">thestoredprocedurenameorT-SQLcommand</param> ///<paramname="commandParameters">anarrayofSqlParamtersusedtoexecutethecommand</param> ///<returns>ASqlDataReadercontainingtheresults</returns> publicstaticSqlDataReaderExecuteReader(stringconnectionString,CommandTypecmdType,stringcmdText,paramsSqlParameter[]commandParameters) { SqlCommandcmd=newSqlCommand(); SqlConnectionconn=newSqlConnection(connectionString); //weuseatry/catchherebecauseifthemethodthrowsanexceptionwewantto //closetheconnectionthrowcode,becausenodatareaderwillexist,hencethe //commandBehaviour.CloseConnectionwillnotwork try { PrepareCommand(cmd,conn,null,cmdType,cmdText,commandParameters); SqlDataReaderrdr=cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); returnrdr; } catch { conn.Close(); throw; } } publicstaticDataSetReturnDataSet(CommandTypecmdType,stringcmdText,paramsSqlParameter[]commandParameters) { SqlCommandcmd=newSqlCommand(); SqlConnectionconn=newSqlConnection(ConnectionStringLocalTransaction); //weuseatry/catchherebecauseifthemethodthrowsanexceptionwewantto //closetheconnectionthrowcode,becausenodatareaderwillexist,hencethe //commandBehaviour.CloseConnectionwillnotwork try { PrepareCommand(cmd,conn,null,cmdType,cmdText,commandParameters); DataSetds=newDataSet(); SqlDataAdaptersda=newSqlDataAdapter(cmd); sda.Fill(ds); returnds; } catch { conn.Close(); throw; } } ///<summary> ///ExecuteaSqlCommandthatreturnsaresultsetagainstthedatabasespecifiedintheconnectionstring ///usingtheprovidedparameters. ///</summary> ///<remarks> ///e.g.: ///SqlDataReaderr=ExecuteReader(SqlConnection,CommandType.StoredProcedure,"PublishOrders",newSqlParameter("@prodid",24)); ///</remarks> ///<paramname="connectionString">avalidconnectionstringforaSqlConnection</param> ///<paramname="commandType">theCommandType(storedprocedure,text,etc.)</param> ///<paramname="commandText">thestoredprocedurenameorT-SQLcommand</param> ///<paramname="commandParameters">anarrayofSqlParamtersusedtoexecutethecommand</param> ///<returns>ASqlDataReadercontainingtheresults</returns> publicstaticSqlDataReaderExecuteReader(SqlConnectionconn,CommandTypecmdType,stringcmdText,paramsSqlParameter[]commandParameters) { SqlCommandcmd=newSqlCommand(); //weuseatry/catchherebecauseifthemethodthrowsanexceptionwewantto //closetheconnectionthrowcode,becausenodatareaderwillexist,hencethe //commandBehaviour.CloseConnectionwillnotwork try { PrepareCommand(cmd,conn,null,cmdType,cmdText,commandParameters); SqlDataReaderrdr=cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); returnrdr; } catch { conn.Close(); throw; } } ///<summary> ///ExecuteaSqlCommandthatreturnsaresultsetagainstthedatabasespecifiedintheconnectionstring ///usingtheprovidedparameters. ///</summary> ///<remarks> ///e.g.: ///SqlDataReaderr=ExecuteReader(connString,CommandType.StoredProcedure,"PublishOrders",newSqlParameter("@prodid",24)); ///</remarks> ///<paramname="connectionString">avalidconnectionstringforaSqlConnection</param> ///<paramname="commandType">theCommandType(storedprocedure,text,etc.)</param> ///<paramname="commandText">thestoredprocedurenameorT-SQLcommand</param> ///<paramname="commandParameters">anarrayofSqlParamtersusedtoexecutethecommand</param> ///<returns>ASqlDataReadercontainingtheresults</returns> publicstaticSqlDataReaderExecuteReader(CommandTypecmdType,stringcmdText,paramsSqlParameter[]commandParameters) { SqlCommandcmd=newSqlCommand(); SqlConnectionconn=newSqlConnection(ConnectionStringLocalTransaction); //weuseatry/catchherebecauseifthemethodthrowsanexceptionwewantto //closetheconnectionthrowcode,becausenodatareaderwillexist,hencethe //commandBehaviour.CloseConnectionwillnotwork try { PrepareCommand(cmd,conn,null,cmdType,cmdText,commandParameters); SqlDataReaderrdr=cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); returnrdr; } catch { conn.Close(); throw; } } ///<summary> ///addparameterarraytothecache ///</summary> ///<paramname="cacheKey">Keytotheparametercache</param> ///<paramname="cmdParms">anarrayofSqlParamterstobecached</param> publicstaticvoidCacheParameters(stringcacheKey,paramsSqlParameter[]commandParameters) { parmCache[cacheKey]=commandParameters; } ///<summary> ///Retrievecachedparameters ///</summary> ///<paramname="cacheKey">keyusedtolookupparameters</param> ///<returns>CachedSqlParamtersarray</returns> publicstaticSqlParameter[]GetCachedParameters(stringcacheKey) { SqlParameter[]cachedParms=(SqlParameter[])parmCache[cacheKey]; if(cachedParms==null) returnnull; SqlParameter[]clonedParms=newSqlParameter[cachedParms.Length]; for(inti=0,j=cachedParms.Length;i<j;i++) clonedParms[i]=(SqlParameter)((ICloneable)cachedParms[i]).Clone(); returnclonedParms; } ///<summary> ///Prepareacommandforexecution ///</summary> ///<paramname="cmd">SqlCommandobject</param> ///<paramname="conn">SqlConnectionobject</param> ///<paramname="trans">SqlTransactionobject</param> ///<paramname="cmdType">Cmdtypee.g.storedprocedureortext</param> ///<paramname="cmdText">Commandtext,e.g.Select*fromProducts</param> ///<paramname="cmdParms">SqlParameterstouseinthecommand</param> privatestaticvoidPrepareCommand(SqlCommandcmd,SqlConnectionconn,SqlTransactiontrans,CommandTypecmdType,stringcmdText,SqlParameter[]cmdParms) { if(conn.State!=ConnectionState.Open) conn.Open(); cmd.Connection=conn; cmd.CommandText=cmdText; if(trans!=null) cmd.Transaction=trans; cmd.CommandType=cmdType; if(cmdParms!=null) { foreach(SqlParameterparmincmdParms) cmd.Parameters.Add(parm); } } ///<summary> ///传入输入参数 ///</summary> ///<paramname="ParamName">存储过程名称</param> ///<paramname="DbType">参数类型</param></param> ///<paramname="Size">参数大小</param> ///<paramname="Value">参数值</param> ///<returns>新的parameter对象</returns> publicstaticSqlParameterMakeInParam(stringParamName,SqlDbTypeDbType,intSize,objectValue) { returnMakeParam(ParamName,DbType,Size,ParameterDirection.Input,Value); } publicvoidMakeInParam(refstringOldString,stringParamName,SqlDbTypeDbType,intSize,objectValue) { OldString=OldString.Replace(ParamName,(string)Value); } ///<summary> ///传入返回值参数 ///</summary> ///<paramname="ParamName">存储过程名称</param> ///<paramname="DbType">参数类型</param> ///<paramname="Size">参数大小</param> ///<returns>新的parameter对象</returns> publicstaticSqlParameterMakeOutParam(stringParamName,SqlDbTypeDbType,intSize) { returnMakeParam(ParamName,DbType,Size,ParameterDirection.Output,null); } ///<summary> ///传入返回值参数 ///</summary> ///<paramname="ParamName">存储过程名称</param> ///<paramname="DbType">参数类型</param> ///<paramname="Size">参数大小</param> ///<returns>新的parameter对象</returns> publicstaticSqlParameterMakeReturnParam(stringParamName,SqlDbTypeDbType,intSize) { returnMakeParam(ParamName,DbType,Size,ParameterDirection.ReturnValue,null); } ///<summary> ///生成存储过程参数 ///</summary> ///<paramname="ParamName">存储过程名称</param> ///<paramname="DbType">参数类型</param> ///<paramname="Size">参数大小</param> ///<paramname="Direction">参数方向</param> ///<paramname="Value">参数值</param> ///<returns>新的parameter对象</returns> publicstaticSqlParameterMakeParam(stringParamName,SqlDbTypeDbType,Int32Size,ParameterDirectionDirection,objectValue) { SqlParameterparam; if(Size>0) param=newSqlParameter(ParamName,DbType,Size); else param=newSqlParameter(ParamName,DbType); param.Direction=Direction; if(!(Direction==ParameterDirection.Output&&Value==null)) param.Value=Value; returnparam; } ///<summary> ///创建SqlCommand对象实例(用来返回一个整数值) ///</summary> ///<paramname="storedProcName">存储过程名</param> ///<paramname="parameters">存储过程参数</param> ///<returns>SqlCommand对象实例</returns> privatestaticSqlCommandBuildIntCommand(SqlConnectionconnection,stringstoredProcName,IDataParameter[]parameters) { SqlCommandcommand=BuildQueryCommand(connection,storedProcName,parameters); command.Parameters.Add(newSqlParameter("ReturnValue", SqlDbType.Int,4,ParameterDirection.ReturnValue, false,0,0,string.Empty,DataRowVersion.Default,null)); returncommand; } ///<summary> ///构建SqlCommand对象(用来返回一个结果集,而不是一个整数值) ///</summary> ///<paramname="connection">数据库连接</param> ///<paramname="storedProcName">存储过程名</param> ///<paramname="parameters">存储过程参数</param> ///<returns>SqlCommand</returns> privatestaticSqlCommandBuildQueryCommand(SqlConnectionconnection,stringstoredProcName,IDataParameter[]parameters) { SqlCommandcommand=newSqlCommand(storedProcName,connection); command.CommandType=CommandType.StoredProcedure; foreach(SqlParameterparameterinparameters) { command.Parameters.Add(parameter); } returncommand; } #region执行查询语句返回dataset ///<summary> ///执行查询语句,返回DataSet ///</summary> ///<paramname="cmdText">查询语句</param> ///<returns>DataSet</returns> publicstaticDataSetGetDataSet(stringcmdText) { using(SqlConnectionconn=newSqlConnection(ConnectionStringLocalTransaction)) { SqlCommandsqlcmd=newSqlCommand(cmdText,conn); sqlcmd.CommandTimeout=1000; SqlDataAdaptercmd=newSqlDataAdapter(sqlcmd); DataSetds=newDataSet(); try { conn.Open(); cmd.Fill(ds,"mydt"); returnds; } catch(Exceptionex) { conn.Close(); cmd.Dispose(); conn.Dispose(); thrownewException(ex.Message); } finally { cmd.Dispose(); conn.Close(); conn.Dispose(); } } } #endregion } #endregion
将C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727/InstallUtil.exe拷贝到执行的目录BinDebug文件下然后注册windows服务
InstallUtil.exewindowservice.exe
卸载windows服务:
InstallUtil.exe-uwindowservice.exe
希望本文所述对大家asp.net程序设计有所帮助。