-2

I work on ASP.NET Core 2.2 Web API and face an issue: I can't use replace function to change the name property of a selected file that I get when uploaded.

When I try like this:

string fileName = DisplayFileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";

I get an error

Iform file doesn't contain definition for replace and no accessible extension method Replace accepting first argument of iformfile

Full sample is here:

[HttpPost, DisableRequestSizeLimit]
public IActionResult Upload()
{
        try
        {
            var DisplayFileName = Request.Form.Files[0];
            string fileName = DisplayFileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
            string Month = DateTime.Now.Month.ToString();
            string DirectoryCreate = myValue1 + Month;

            Path.Combine(Directory.GetCurrentDirectory(), folderName);

            if (!Directory.Exists(DirectoryCreate))
            {
                Directory.CreateDirectory(DirectoryCreate);
            }

            if (DisplayFileName.Length > 0)
            {
                var filedata = ContentDispositionHeaderValue.Parse(Request.Form.Files[0].ContentDisposition).FileName.Trim('"');
                var dbPath = Path.Combine(DirectoryCreate, fileName);
              
                using (var stream = new FileStream(dbPath, FileMode.Create))
                {
                    Request.Form.Files[0].CopyTo(stream);
                }

                return Ok(new { dbPath });
            }
            else
            {
                return BadRequest();
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, $"Internal server error: {ex}");
        }
}

How to solve this issue? sample

suppose i select file developed.xlsx

then after use replace or any way result will be

developed-sddfn78888.xlsx

1 Answer 1

1

You can use System.IO.Path to get filename and get file extension from request files. Change this string fileName = DisplayFileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx"; To

string filename = Path.GetFileName(DisplayFileName.FileName);
string fileExtension = Path.GetExtension(DisplayFileName.FileName);
string newFileName = $"{filename}-{Guid.NewGuid().ToString()}{fileExtension}";

Otherwise, you could modify your code to

 string fileName = DisplayFileName.FileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.