Neeraj
Neeraj

Reputation: 38

How to close file stream in .netcore

I am new to .net core and c#. I have a file upload requirement in my project. I am trying to upload my file to aws s3. I upload file from a folder in my project root folder and then delete the uploaded file from there. But when I try to upload to s3 I am getting following error

The process cannot access the file because it is being used by another process.

Here is my code to upload file

string fileFolder = Path.Combine(hostingEnvironment.WebRootPath, "TempFiles");
                    uniqueFileName1 = Guid.NewGuid().ToString() + "_" + cm.UDocument1.FileName;
                    string filePath = Path.Combine(fileFolder, uniqueFileName1);
                    cm.UDocument1.CopyTo(new FileStream(filePath, FileMode.Create));

                    var tempPath = Path.Combine(hostingEnvironment.WebRootPath, "TempFiles", Path.GetFileName(uniqueFileName1));
                    UploadFile(cm.UDocument1,tempPath);

[HttpPost]
    public ActionResult UploadFile(IFormFile file,string path)
    {

        var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion);

        var fileTransferUtility = new TransferUtility(s3Client);
        try
        {
            if (file.Length > 0)
            {

                var fileTransferUtilityRequest = new TransferUtilityUploadRequest
                {
                    BucketName = bucketName,
                    FilePath = path,
                    StorageClass = S3StorageClass.Standard,
                    Key = file.FileName
                };
                fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
                fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
                fileTransferUtility.Upload(fileTransferUtilityRequest);
                fileTransferUtility.Dispose();

                string[] tmp = { "" };
                tmp = fileName.Split("-");

            }
            ViewBag.Message = "File Uploaded Successfully!!";

            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }
        }

        return ViewBag.Message;

    }

what can I do about it?

Upvotes: 1

Views: 1359

Answers (1)

Josh
Josh

Reputation: 299

On this line:

cm.UDocument1.CopyTo(new FileStream(filePath, FileMode.Create));

You create a file stream but you dont dispose it.

wrap in a using statement instead:

using (var iNeedToLearnAboutDispose = new FileStream(filePath, FileMode.Create))
{
    cm.UDocument1.CopyTo(iNeedToLearnAboutDispose);
}

Upvotes: 1

Related Questions