【发布时间】: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,它必须是特定格式。但是即使可以,即使文件名不是唯一的,创建唯一标识也无法解决您的问题。您可能会考虑在数据上构建散列。