how to use "using" with httppostedfilebase in c#

66 views Asked by At

I need to free the process or close the file of httppostedfilebase , so i don't know how to use using with httppostedfilebase , i need to do something like this :

 using (var myFile = Request.Files[0])
   {
   // do something
   }
1

There are 1 answers

0
Amjad S. On

you can use IFormFile .IFormFile is in the following namespace Microsoft.AspNetCore.Http.

public FileDetails UploadSingle(IFormFile file)
{
    FileDetails fileDetails;
    using (var reader = new StreamReader(file.OpenReadStream()))
    {
        var fileContent = reader.ReadToEnd();
        var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
        fileDetails = new FileDetails
        {
            Filename = parsedContentDisposition.FileName,
            Content = fileContent
        };
    }

    return fileDetails;
}

for multuple files

public FileDetails UploadSingle(List<IFormFile> Files)
{
        string wwwPath = this.Environment.WebRootPath;
        string contentPath = this.Environment.ContentRootPath;
 
        string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
 
        List<string> uploadedFiles = new List<string>();
        foreach (IFormFile postedFile in Files)
        {
            string fileName = Path.GetFileName(postedFile.FileName);
            using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
            {
               ....
            }
        }
}