0

我在"~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)));
}

我的问题是:用户可以上传任一".doc", ".docx", ".xls", ".xlsx", or ".pdf"格式文件。现在,当用户上传".doc"格式文件时,它会上传到文件夹中。稍后同一用户可以上传".pdf"格式的文件,该文件也上传到文件夹中。这意味着用户可以上传两个文件。

现在我要做的是:
当特定用户上传他的文档时:
->搜索用户上传的文档是否在该文件夹中。即具有不同扩展名的特定文件名是否存在。
-> 如果文件名已经存在,但扩展名不同,则删除该文件并上传新文件。

4

3 回答 3

4

试试这个,只是另一种方式;如果您的文件名是"document"

string[] files = System.IO.Directory.GetFiles(fullpath,"document.*");
foreach (string f in files)
{
   System.IO.File.Delete(f);
}

所以你的代码是;

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)));
}
于 2012-12-07T09:08:35.967 回答
2

像这样的东西应该可以解决问题

  var files = new DirectoryInfo(fullpath).GetFiles();
  var filesNoExtensions = files.Select(a => a.Name.Split('.')[0]).ToList();
    //for below: or 'document' if that's what you rename it to be on disk
  var fileNameNoExtension = fileName.Split('.')[0]; 
  if (filesNoExtensions.Contains(fileNameNoExtension))
  {
    var deleteMe = files.First(f => f.Name.Split('.')[0] == fileNameNoExtension);
    deleteMe.Delete();
  }
  file.SaveAs(Path.Combine(fullpath,"document"+Path.GetExtension(fileName)));
于 2012-12-07T08:57:39.457 回答
0

Get the filename of the new file without extension, then loop through all the filenames in the folder where it will be uploaded to and check if the name already exists. If so, delete the old an upload, else upload.

var info = new FileInfo("C:\\MyDoc.docx");
var filename = info.Name.Replace(info.Extension, "");
var files = Directory.GetFiles("YOUR_DIRECTORY").Select(f => new FileInfo(f).Name);

if (files.Any(file => file.Contains(filename)))
{
    //Delete old file
}
//Upload new file
于 2012-12-07T09:03:28.443 回答