【问题标题】:C# Error - Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)C# 错误 - Guid 应包含 32 位数字和 4 个破折号 (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
【发布时间】:2021-10-13 15:11:16
【问题描述】:

我想将传入的照片保存到文件夹中。我想将名称保存为 Guid,这样当同名文件进入时就没有问题,但我的代码中似乎有错误。我没用过guid,也不知道怎么用。

public async Task<ApiResponse<SliderResponse>> Handle(SliderCreate request, CancellationToken cancellationToken)
    {
        byte[] bytes = null;

        using (BinaryReader br = new BinaryReader(request.file.OpenReadStream()))
        {
            bytes = br.ReadBytes((int)request.file.OpenReadStream().Length);
        }

        Guid ImageFileName = new Guid ((request.file.FileName).ToString());
        var FileContentType = request.file.ContentType;
        var ImageContent = bytes;

        using (var ms = new MemoryStream(bytes))
        {
            var path = Environment.CurrentDirectory + @"\File";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            using (var fs = new FileStream(path+ @"\" + ImageFileName , FileMode.Create ))
            {
                ms.WriteTo(fs);
            }
        }

        var mapped = _mapper.Map<Slider>(request);

        if (mapped == null)
            return new ErrorApiResponse<SliderResponse>(ResultMessage.NotCreatedSlider);

        var model = await _repo.Sliders.AddAsync(mapped);

        var response = _mapper.Map<SliderResponse>(model);

        return new SuccessApiResponse<SliderResponse>(response);
    }

【问题讨论】:

  • 您不能将任意字符串转换为 Guid,它必须是特定格式。但是即使可以,即使文件名不是唯一的,创建唯一标识也无法解决您的问题。您可能会考虑在数据上构建散列。

标签: c# .net-core


【解决方案1】:

删除

Guid ImageFileName = new Guid ((request.file.FileName).ToString());

(因为传递给 Guid 构造函数的字符串应该是表示 Guid 的字符串 - 它类似于 Guid.Parse。不要传递不代表 Guid 的字符串,例如“IMG_0123.JPG”您的用户刚刚上传 - 此图像文件名不代表 guid)

改变

using (var fs = new FileStream(path+ @"\" + ImageFileName , FileMode.Create ))

using (var fs = new FileStream(Path.Combine(path, Guid.NewGuid().ToString()) , FileMode.Create ))

使用 Path.Combine 组合路径。它了解运行它的系统的不同目录分隔符。如果你硬编码一个 windows 反斜杠然后在 Linux 上运行你的应用程序,你会得到一个惊喜.. Path.Combine 接受 N 个参数并将它们构建成一个路径。查看 Path 中可用的其他方法 - 那里有一些方便的东西


如果您希望文件具有扩展名,可以使用 Path.GetExtension(request.file.FileName) 将其从请求文件名中拉出,并将其添加到 Guid 字符串中,例如 Path.Combine(path, $"{Guid.NewGuid()}{Path.GetExtension(request.file.FileName)}")

您也不需要在调用 CreateDirectory 之前检查目录是否存在 - 在存在的目录上调用 CreateDirectory 是非操作

【讨论】:

  • 我试过了,它部分有效。保存为guid,但是文件是空的,所以照片的名字变了,但是照片没有来。
  • 这与当前问题无关;你应该问一个新问题。解决了“为什么会出现 Guid 格式 xxxx 这个异常”的问题。问一个新问题没问题,所以我们不应该开始问一件事,然后一遍又一遍地改变问题(“哦,现在文件是空的”,“哦,现在文件没有保存到数据库”,“哦,现在图片没有出现在网页的缩略图中..”),直到我们调试了整个应用程序..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多