【问题标题】:How to check if the filename already exists如何检查文件名是否已经存在
【发布时间】:2021-11-28 18:38:55
【问题描述】:

我几乎不需要帮助来修改我的功能。如何检查文件是否已存在同名文件?如果确实如此,则在名称中添加一个 newguid 字符串并保存新文件。

public string UploadStorageFile(StorageModel newFile, int userId)
{
    string uniqueFileName = null;
    if(newFile.FileName != null)
    {
        string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, $"repositories/{userId}");
        if (!Directory.Exists(uploadsFolder))
        {
            Directory.CreateDirectory(uploadsFolder);
        }
        uniqueFileName = Guid.NewGuid().ToString() + "_" + newFile.FileName.FileName;
        string filePath = Path.Combine(uploadsFolder, uniqueFileName);
        using(var fileStream = new FileStream(filePath, FileMode.Create))
        {
            newFile.FileName.CopyTo(fileStream);
        }
    }

    return uniqueFileName;
}

【问题讨论】:

  • Soo,您已成功将 Directory.Exists 放入您的代码中;为什么不尝试文件的显而易见的事情?
  • 顺便说一句,创建一个已经存在的目录是无操作的;你不需要 Directory.Exists 先检查
  • 请记住,您有潜在的并发问题。您可以使用File.Exists(),但该文件可能在一毫秒内不存在,然后第二个用户在您的代码继续之前上传同名文件。根据您的用例,这可能不太可能,但请注意这种可能性。

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

为了检查,如果一个文件已经存在,你可以使用File.Exists()方法。

这是一个基本示例,关于如何检查文件是否已经存在:

    public bool DoesFileAlreadyExist(string uploadFolder, string fileName)
    {
        var file = $"{uploadFolder}\{fileName}";
        return File.Exists(file);
    }

具体到您的代码,您可以使用本例中的方法(只需调用该方法,并检查它是否存在):

public string UploadStorageFile(StorageModel newFile, int userId)
{
    string uniqueFileName = null;
    if(newFile.FileName != null)
    {
        string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, $"repositories/{userId}");
        if (!Directory.Exists(uploadsFolder))
        {
            Directory.CreateDirectory(uploadsFolder);
        }

        if (!DoesFileAlreadyExist(uploadsFolder, newFile.Filename)
        {
        
        uniqueFileName = Guid.NewGuid().ToString() + "_" + newFile.FileName.FileName;
        string filePath = Path.Combine(uploadsFolder, uniqueFileName);
        using(var fileStream = new FileStream(filePath, FileMode.Create))
        {
            newFile.FileName.CopyTo(fileStream);
        }
    }

    return uniqueFileName;
    }
return "NO FILE CREATED";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 2016-08-08
    • 2013-10-28
    • 2022-08-19
    • 1970-01-01
    相关资源
    最近更新 更多