删除同名文件,扩展名并不重要 [英] Removing the file with same name, extension doesn't matter

查看:140
本文介绍了删除同名文件,扩展名并不重要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某些文件〜内容/文档持有每个上传的文件文件夹中。在我的情况下,用户只能上传一个文件。

I have some files in "~Content/Documents" folder which holds every uploaded file. In my case the user can only upload one file.

我也做了部分上传,用户可以上传自己的文件。

I have done the uploading part where the user can upload his file.

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)));
}

我的问题是:
用户可以上传任何文档,.DOCX,是.xls,.XLSX或.PDF格式的文件。
现在,当用户上传DOC格式的文件时,它被上传到文件夹中。后来,同一个用户可以上传PDF格式,也上传到该文件夹​​的文件。这意味着用户可以上传两个文件。

My problem is: User can upload either ".doc", ".docx", ".xls", ".xlsx", or ".pdf" format files. Now when the user upload the file of ".doc" format it is uploaded to the folder. Later the same user can upload the file of ".pdf" format which is also uploaded to the folder. That means the user can upload two files.

现在我想要做的是:

当一个特定的用户上传自己的文档:

- >搜索用户上载的文件是否在该文件夹或没有。即不同后缀的具体文件存在与否。

- >如果文件名已经不同后缀存在,那么删除该文件并上传新文件

Now what I want to do is:
When a specific user uploads his document:
->search whether the document uploaded by the user is in that folder or not. i.e. the specific filename with different extension exists or not.
->if the filename already exists with different extension then remove that file and upload the new file.

推荐答案

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

Try this, Just another way; If your filename is "document"

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

所以,你的code会;

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)));
}

这篇关于删除同名文件,扩展名并不重要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆