【发布时间】: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