典型應用:
建立檔案:首先判斷伺服器上檔案是否存在,如果存在則出現提示框:是否需要覆寫?如果确認覆寫則繼續建立檔案,否則直接傳回
解決方法:
增加兩個按鈕,其中一個隐藏:
<input type=button runat=server id=btnChk value="建立檔案" onserverclick="btnChk_ServerClick"/>
<input type=button runat=server id=btnCrtFil onserverclick="btnCrt_ServerClick" style='visibility:hidden' />
btnChk_ServerClick事件主要代碼如下:

CrtFilChk(filename,'btnCrtFil',Page);

btnCrt_ServerClick事件主要代碼如下:

CreateFile(filename,Page);
先判斷如在則采用__doPostBack調用伺服器端控件的代碼

public void CrtFilChk(string strFileName,string HidControlID,Page srcPage)
{
try
{
string strTmp ="";
//删除舊檔案
if (File.Exists(strFileName))
{
strTmp= strFileName.Replace("\\", "/");
srcPage.RegisterStartupScript(System.Guid.NewGuid().ToString(),
"<script> if(('覆寫嗎?')){__doPostBack('"+HidControlID+"','');}</script>");
}
else
CreateFil(strFileName,srcPage);
}
}
catch (Exception e)
{
HttpContext.Current.Response.Write("<script defer>alert('操作失敗,因為"+e.Message+"')</script>");
}
}

建立檔案

public void CreateFile(string strFileName)
{
strFileName= strFileName.Replace("\\", "/");
//删除舊檔案
{
File.Delete(strFileName);
}
string strTmp ="檔案内容
.";
StreamWriter sw = new StreamWriter(strFileName, false, System.Text.Encoding.GetEncoding("gb2312"));
sw.Write(strTmp);
sw.Close();
HttpContext.Current.Response.Write("<script defer>alert('建立檔案" + strFileName + "成功!')</script>");
}
{
HttpContext.Current.Response.Write("<script defer>alert('建立檔案" + strFileName + "失敗,因為"+e.Message+"!')</script>");
}
}

本文轉自 liudao 部落格園部落格,原文連結:xxhttp://www.cnblogs.com/liudao/archive/2007/04/28/731034.html如需轉載請自行聯系原作者