多看帮助文档,不让自己OUT了

在ASP.NET1.1的时候,上传文件代码:

//上传版面图片
private void UpLoadPicture(MagazineLayout layout)
{
//不上传附件时直接返回0作为附件ID
if (String.IsNullOrEmpty(PictureName.PostedFile.FileName))
{
return;
}

string oldPicturePath = "";
if (!string.IsNullOrEmpty(layout.PicturePath))
{
oldPicturePath
= Server.MapPath(layout.PicturePath);
}

const string path = "/MagazineLayout/";

//文件名(文件名+后缀)
layout.PictureName = PictureName.PostedFile.FileName.Substring(PictureName.PostedFile.FileName.LastIndexOf('\\') + 1);

//文件扩展名
string fileTitleSuf = layout.PictureName.Substring(layout.PictureName.LastIndexOf('.'));

//文件保存虚拟路径
layout.PicturePath = path + Session["UserId"] + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + fileTitleSuf;

//文件保存物理路径
string filePath = Server.MapPath(layout.PicturePath);

try
{
if (File.Exists(filePath.Replace("\\", "\\\\")))
{
Response.Write(
"<script>alert('上传文件名称重复,操作未成功!')</script>");
}
else
{
//文件|附件保存到文件夹
PictureName.PostedFile.SaveAs(filePath);

//如果是覆盖,则删掉原来的文件
if (!String.IsNullOrEmpty(oldPicturePath))
{
//重新上传了一次附件时,将原来的附件删除
if (File.Exists(oldPicturePath))
{
File.Delete(oldPicturePath);
}
}

//信息保存到数据库
MagazineManager.CreateUpdateDeleteMagazineLayout(layout, MagazineDataProviderAction.UpdateMagazine);
}
}
catch (Exception err)
{
Response.Write(err.Message);
Response.Write(
"<script>alert('文件上传失败!');</script>");
}

return;
}

偶然的机会看了下新的API,太让人震撼了,原来自己OUT那么远了。。。。。。

private void UpLoadFile(MagazineLayout layout)
{
if (String.IsNullOrEmpty(PictureName.PostedFile.FileName))
{
return;
}

if(!String.IsNullOrEmpty(layout.PicturePath))
{
//删除老的文件
DeleteOldFile(layout.PicturePath);
}

const string path = "/MagazineLayout/";

try
{
//文件后缀名
string fileExt = Path.GetExtension(PictureName.PostedFile.FileName);

//新文件名(文件名+后缀名)
string fileName = Session["UserId"] + DateTime.Now.ToString("yyyyMMddhhmmss") + fileExt;

//原文件名(文件名+后缀)
layout.PictureName = Path.GetFileName(PictureName.PostedFile.FileName);

//文件保存虚拟路径
layout.PicturePath = path + fileName;

string dir = Request.MapPath(path);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);

//保存文件
PictureName.PostedFile.SaveAs(Path.Combine(dir + fileName));

//信息保存到数据库
MagazineManager.CreateUpdateDeleteMagazineLayout(layout, MagazineDataProviderAction.UpdateMagazine);
}
catch (Exception err)
{
Response.Write(err.Message);
Response.Write(
"<script>alert('文件上传失败!');</script>");
}

}

//文件删除方法
private static void DeleteOldFile(string filePath)
{
//重新上传了一次附件时,将原来的附件删除
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}

在.NET Framework 4 很多方法已经封装好了,所有新的API不能落下了,赶紧补

posted @ 2011-08-05 16:56  polymorphic  阅读(343)  评论(1编辑  收藏  举报