日期:2014-05-18 浏览次数:20440 次
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; //Directory, Path, FileInfo using System.Text; //StringBuilder public partial class _Default : System.Web.UI.Page { private const string TARGET_DIR = "~/"; protected void btnSubmit_Click(object sender, EventArgs e) { //Check target directory string sTargetDir = Request.MapPath(TARGET_DIR); System.Diagnostics.Debug.Assert(Directory.Exists(sTargetDir)); StringBuilder objDisplay = new StringBuilder(); objDisplay.Append("<h3>You have just saved:</h3><ul>"); //Iterate through posted files (foreach does not work with empty file inputs) for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFile objFile = Request.Files[i]; //Make sure file input has content if ((objFile.ContentLength > 0) && (objFile.FileName.Length > 0)) { //Get target file path for save as string sFileName = Path.GetFileName(objFile.FileName); string sFilePath = Path.Combine(sTargetDir, sFileName); FileInfo objFileInfo = new FileInfo(sFilePath); //No business rule, i.e. we just want to avoid failure if (objFileInfo.Exists) { objFileInfo.Attributes &= ~FileAttributes.ReadOnly; objFileInfo.Delete(); } //Save file objFile.SaveAs(sFilePath); //Append link objDisplay.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", this.ResolveUrl(Path.Combine(TARGET_DIR, sFileName)), sFileName); } } objDisplay.Append("</ul>"); litDisplay.Text = objDisplay.ToString(); } }