问题描述
比较下面两个按钮方法:第一个成功实现,第二个第一次单击没有返回,第二次点击显示文件“E:_WebmyManageadminfrm_top.htm”正由另一进程使用,因此该进程无法访问该文件。protectedvoidButton1_Click(objectsender,EventArgse){System.IO.StreamWritersw1=newSystem.IO.StreamWriter(Server.MapPath("frm_left.htm"),false,System.Text.Encoding.GetEncoding("gb2312"));Server.Execute("frm_left.aspx",sw1);sw1.Close();}protectedvoidButton2_Click(objectsender,EventArgse){System.IO.StreamWritersw1=newSystem.IO.StreamWriter(Server.MapPath("frm_top.htm"),false,System.Text.Encoding.GetEncoding("gb2312"));Server.Execute("frm_top.aspx",sw1);sw1.Close();}
frm_left.aspx和frm_top.aspx略有区别,frm_top.aspx中用到了模板化usingNVelocity;usingNVelocity.Context;usingSystem;usingSystem.Web;publicpartialclassadmin_top:System.Web.UI.Page{protectedvoidPage_Load(objectsender,EventArgse){IContextcontext=newVelocityContext();context.Put("secondBtn","首页");context.Put("btnAct","window.open('../')");context.Put("btnImg","images/icon/search.gif");Response.Write(FastTemplate.Merge(context,"VM_lqb/top.vm"));Response.End();Page.Dispose();}}
publicclassFastTemplate{publicFastTemplate(){}publicstaticstringMerge(NVelocity.Context.IContextcontext,string模板文件名){VelocityEnginevelocity=newVelocityEngine();ExtendedPropertiesprops=newExtendedProperties();props.AddProperty(RuntimeConstants.RESOURCE_LOADER,"file");props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,HttpContext.Current.Server.MapPath("./"));props.AddProperty(RuntimeConstants.INPUT_ENCODING,"gb2312");props.AddProperty(RuntimeConstants.OUTPUT_ENCODING,"gb2312");velocity.Init(props);Templatetemp=velocity.GetTemplate(模板文件名);StringWriterwriter=newStringWriter();temp.Merge(context,writer);Strings=writer.ToString();writer.Close();writer.Dispose();returns;}}
解决方案
解决方案二:
System.IO.FileStream_FileStream=newSystem.IO.FileStream(Server.MapPath("frm_left.htm"),System.IO.FileMode.Open,System.IO.FileAccess.ReadWrite,System.IO.FileShare.ReadWrite);byte[]_ReadByte=newbyte[_FileStream.Length];_FileStream.Read(_ReadByte,0,_ReadByte.Length);_FileStream.Close();
设置System.IO.FileShare.ReadWriteB/S下可能是你在打开还没有关闭文件引起的.
解决方案三:
帮顶。。要不你试试,第一个按钮事件中System.IO.StreamWriter的对象sw1第二个按钮事件中System.IO.StreamWriter的对象改成sw2
解决方案四:
问题关键在于Server.Execute("frm_top.aspx",sw1);我尝试用下面的方法获取frm_top.aspx即可成功,各位能否给我讲下Server方法有什么限制?为什么获取不到?System.Net.WebClientwc=newSystem.Net.WebClient();System.IO.Streams=wc.OpenRead(Request.Url.ToString().Replace("page_static.aspx","frm_top.aspx"));……
解决方案五:
文件操作和数据库操作建议必须加上trycatchfinally语法。因为这些访问很很容易出错。
解决方案六:
用using打开文件,处理后马上自动关闭