Brandon Turpy
Brandon Turpy

Reputation: 921

How to change file name when uploading using IFormFile

I have the following code (I am still developing it) that successfully uploads a file to the needed path.

   private async Task AddImage(IFormFile image, string filePath)
    {
      List<string> PermittedFileTypes = new List<string> {
        "image/jpeg",
        "image/png",
      };


      if (PermittedFileTypes.Contains(image.ContentType)) {

        // HERE I WILL CHECK NAME AND CHANGE IF IT ALREADY EXSISTS

        using (var stream = new FileStream(Path.Combine(filePath, image.FileName), FileMode.Create))
        {
          await image.CopyToAsync(stream);
        }
      } 
    }

I am coming along issues, where files are attempting to be uploaded with the same name (obviously getting errors), but a different file. So I want to check if the file exists, and if it does change the name of the file, probably append a "_#) to the end and then upload the file again under the new name. Problem is the IFormFile.FileName is only for get, and I am not able to set the file name.

Looking online I see where people suggest copying the file to a new name, but since the file is not able to be uploaded I can not do that. Any help is appreciated!

Upvotes: 7

Views: 12856

Answers (2)

David Charles
David Charles

Reputation: 557

The below code snippet might help, I just used a different file name "thefile" when creating the stream.

public async Task<dynamic> AddFile(IFormFile FormFile, string thefile="newfilename.png", string filePath= @".\DocumentStoredHere\")
    {
        try
        {
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            using (var stream = System.IO.File.Create(thefile))
            {
                await FormFile.CopyToAsync(stream);
            }
            return true;
        }
        catch (System.Exception ex)
        {
            Console.WriteLine(ex.Message);
            return false;
        }
    }

Upvotes: 1

Majdi Saibi
Majdi Saibi

Reputation: 435

You can use Path.Combine(filePath, Guid.NewGuid() ) instead of Path.Combine(filePath, image.FileName) to garantee that the filename is unique.

Upvotes: 8

Related Questions