Gearoid Sheehan
Gearoid Sheehan

Reputation: 308

Change name of uploaded IFormfile in ASP .NET Core

I am uploading a csv file from Angular to my ASP .NET Core application. I would like to rename the file to a Guid but when trying to access the filename I am receiving the error "The property or indexer IFormfile.Filename cannot be assigned to -- it is read only". How can I work around this in order to change the files name?

    public async Task<bool> CreateNewSurvey(SurveyDto surveyDto)
    {
        var S3FilenameGuid = Guid.NewGuid();

        Survey survey = new Survey
        {
            SurveyName = surveyDto.surveyName,
            StartDate = surveyDto.startDate,
            EndDate = surveyDto.endDate,
            S3Filename = S3FilenameGuid.ToString() + ".xlsx",
            CompanyId = new Guid(surveyDto.companyId),
            SurveyDescription = surveyDto.surveyDescription
        };

        // Receiving Error here
        var file = surveyDto.file;
        file.FileName= S3FilenameGuid.ToString();


        AmazonS3Uploader amazonS3Uploader = new AmazonS3Uploader();
        await amazonS3Uploader.UploadFileAsync(file);

        return await _surveyRepository.CreateNewSurvey(survey);
    }

Upvotes: 0

Views: 2009

Answers (3)

Iria
Iria

Reputation: 497

I would do the following:

using (var stream = System.IO.File.Create(S3Filename + ".xlsx"))
{
    await file.CopyToAsync(stream);
}

try{File.Delete(file);}
catch(.........){}

It's basically, what is been suggested already: you said that you want to work around the file name changes, it is been suggested to copy the file with a different name. The problem I see with that is that you may end up with plenty files, while you may want only one, so delete the original file and it will work as a change of file name. If this is not possible, then you use blocks finally and catch to control your options (what you want to do in those cases). This may solve a disk space issue when copying the file multiple times. File is the old name for the file, the one that you want to rename.

Upvotes: 0

TheMixy
TheMixy

Reputation: 1296

Add some properties before uploading and put your custom filename/guid there. See this example: Amazon S3 demo

Upvotes: 1

Steve
Steve

Reputation: 216273

Don't try to change that property, instead, save the IFormFile with the name you want.

using (var stream = System.IO.File.Create(S3Filename + ".xlsx"))
{
    await file.CopyToAsync(stream);
}

Also, probably you want to add some file path to the file. I don't think you want to save to the root of you site.

Upvotes: 1

Related Questions