You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

上传同名文件时如何在同路径下重命名以避免覆盖?

解决上传文件同名自动重命名问题

要实现同名文件上传时自动重命名(如file.pdf存在时改为file(1).pdf),你可以添加一个生成唯一文件路径的辅助方法,同时优化流资源的处理。

步骤1:添加生成唯一文件路径的方法

这个方法会检查目标路径是否存在文件,若存在则递增序号生成新路径:

private string GetUniqueFilePath(string directory, string fileName)
{
    string fileExtension = Path.GetExtension(fileName);
    string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
    string newFilePath = Path.Combine(directory, fileName);
    int counter = 1;

    while (File.Exists(newFilePath))
    {
        newFilePath = Path.Combine(directory, $"{fileNameWithoutExtension}({counter}){fileExtension}");
        counter++;
    }

    return newFilePath;
}

步骤2:修改上传方法

替换原代码中生成文件路径的逻辑,同时用using语句自动管理流资源(避免手动关闭的繁琐和资源泄漏):

private async Task OnInputFile(InputFileChangeEventArgs e)
{
    selectedFiles = e.GetMultipleFiles();
    Message = $"{selectedFiles.Count} file(s) selected";
    this.StateHasChanged();

    var uploadDirectory = Path.Combine(Directory.GetCurrentDirectory(), "FilePath");
    // 确保上传目录存在,防止因目录不存在报错
    Directory.CreateDirectory(uploadDirectory);

    foreach (var file in selectedFiles)
    {
        using Stream stream = file.OpenReadStream(maxAllowedSize: 10_000_000);
        string path = GetUniqueFilePath(uploadDirectory, file.Name);
        
        using FileStream fs = File.Create(path);
        await stream.CopyToAsync(fs);
    }
    
    Message = $"{selectedFiles.Count} file(s) uploaded on server";
    this.StateHasChanged();
}

关键说明

  • 辅助方法会循环检查文件是否存在,每次递增括号内的数字,直到找到未被占用的文件路径
  • using语句会在代码块结束后自动释放流资源,比手动调用Close()更安全可靠
  • 提前创建上传目录,避免因目标目录不存在导致的IO异常

内容的提问来源于stack exchange,提问作者Addlon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:05:24