Reputation:
I want to save the incoming photo to the folder. I want to save the names as Guids so that there is no problem when a file with the same name comes in, but there seems to be an error in my code. I didn't use a guid and I don't know how to use it.
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);
}
Upvotes: 0
Views: 1248
Reputation: 74730
Remove
Guid ImageFileName = new Guid ((request.file.FileName).ToString());
(because the string you pass into a Guid constructor should be a string that represents a Guid - it is similar to Guid.Parse. Don't pass a string that is not representative of a Guid, like "IMG_0123.JPG" your user just uploaded - this image file name does not represent a guid)
Change
using (var fs = new FileStream(path+ @"\" + ImageFileName , FileMode.Create ))
To
using (var fs = new FileStream(Path.Combine(path, Guid.NewGuid().ToString()) , FileMode.Create ))
Use Path.Combine to combine paths. It understands the different directory separator chars of the system it is running on. If you hard code a windows backslash and then run your apps on Linux, you'll get a surprise.. Path.Combine takes N number of arguments and builds them into a path. Check out the other methods available in Path- some handy stuff in there
If you want the file to have an extension, maybe pull it off the request filename with Path.GetExtension(request.file.FileName)
and add it to the Guid string like Path.Combine(path, $"{Guid.NewGuid()}{Path.GetExtension(request.file.FileName)}")
You also don't need to check if a directory exists before you call CreateDirectory- calling CreateDirectory on a dir that exists is a non-op
Upvotes: 2