Sur*_*tha 0 c# asp.net-mvc file-extension razor asp.net-mvc-3
我的文件夹中有一些文件"~Content/Documents",其中包含每个上传的文件。就我而言,用户只能上传一个文件。
我已经完成了上传部分,用户可以上传他的文件。
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var fullpath = System.Web.HttpContext.Current.Server.MapPath("~/Content/Documents");
file.SaveAs(Path.Combine(fullpath,"document"+Path.GetExtension(fileName)));
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:用户可以上传任一".doc", ".docx", ".xls", ".xlsx", or ".pdf"格式的文件。现在,当用户上传格式文件时,".doc"它会上传到该文件夹。稍后,同一用户可以上传该".pdf"格式的文件,该文件也会上传到该文件夹。这意味着用户可以上传两个文件。
现在我想做的是:
当特定用户上传他的文档时:
->搜索该用户上传的文档是否在该文件夹中。即具有不同扩展名的特定文件名是否存在。
->如果文件名已存在且具有不同的扩展名,则删除该文件并上传新文件。
试试这个,只是另一种方式;如果你的文件名是"document"
string[] files = System.IO.Directory.GetFiles(fullpath,"document.*");
foreach (string f in files)
{
System.IO.File.Delete(f);
}
Run Code Online (Sandbox Code Playgroud)
所以你的代码是;
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var fullpath = System.Web.HttpContext.Current.Server.MapPath("~/Content/Documents");
//deleting code starts here
string[] files = System.IO.Directory.GetFiles(fullpath,"document.*");
foreach (string f in files)
{
System.IO.File.Delete(f);
}
//deleting code ends here
file.SaveAs(Path.Combine(fullpath,"document"+Path.GetExtension(fileName)));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5495 次 |
| 最近记录: |