C# 上传下载文件

 

 

代码
protected void btnFileUpload_Click(object sender, EventArgs e)
{
int fileSize = FileUpload1.PostedFile.ContentLength;
//string fileName = FileUpload1.PostedFile.FileName; //全路径
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
if (fileName != "")
{
//True不存在同名文件
bool flag = IsExistSameFile(Server.MapPath("..\\FilesPublic"), fileName);
if (flag)
{
FileUpload1.PostedFile.SaveAs(Server.MapPath(
"..\\FilesPublic\\") + fileName);

}

}

}

//文件夹中是否存在同名文件

public bool IsExistSameFile(string filePath, string fileName)
{
bool flag
= true;
FileInfo[] NewFileInfo;
//定义一个数组,储存找到的文件并作为返回值
DirectoryInfo FatherDirectory = new DirectoryInfo(filePath); //创建一个当前目录的实例
NewFileInfo = FatherDirectory.GetFiles();
//遍历文件夹
foreach (FileInfo NextFolder in NewFileInfo)
{
if (fileName == NextFolder.Name)
{
flag
= false;
}
}
return flag;
}



//下载文件,弹出另存为对话框

protected
void lbDownLoad_Click(object sender, EventArgs e)
{
LinkButton lb
= (LinkButton)sender;
string id
= lb.CommandArgument;
DataSet ds
= WFInfo.Business.FileManager.FileNameByID(id);
string fileName
= ds.Tables[0].Rows[0]["FileName"].ToString();

string filepath
= Server.MapPath("../FilesPublic/" + fileName);
string filename
= System.IO.Path.GetFileName(filepath);
Response.Clear();
Response.ContentType
= "application/octet-stream";
Response.AppendHeader(
"Content-Disposition", "attachment;filename=" + filename);
Response.TransmitFile(filepath);
Response.Flush();
Response.Close();
}

 

posted on 2010-10-29 18:17  Paste  阅读(172)  评论(0编辑  收藏  举报

导航