0

I'm using visual studio 2022 dot net core6 and i want to save image file stream in my folder i have used stream files written to successfully but i want to avoid this exception

Exception:

The process cannot access the file 'D:\muthu\ads\Screenshot (1).png' because it is being used by another process.

code:

var file = contents.File;
                var fileCount = contents.File.Length;
                var folderName = Path.Combine("Uploads");

                var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
                if (file.Length > 0)
                {
                    string uploadsFolder = Path.Combine(environment.ContentRootPath, "Uploads");
                    var uniqueFileName = file.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    //File.Create(filePath);
                    //using (var fileStream = new FileStream(filePath, FileMode.Create))
                    //{
                    //  file.CopyTo(fileStream);
                    //}
                    using (var stream = System.IO.File.Create(filePath))
                    {
                        await file.CopyToAsync(stream); //exception line
                    }

2 Answers2

1

Because of access to the file is lock due to it's using by another person or task.

From .net 6 it is better to use filestream instead. And set FileShare option to share the file.

https://devblogs.microsoft.com/dotnet/file-io-improvements-in-dotnet-6/

Mohammad Reza Mrg
  • 1,552
  • 15
  • 30
0

i want to avoid this exception

A "file in use" exception is an exogenous exception, so it cannot be avoided. It can, however, be caught and handled.

If you want to build retries (e.g., retry once per second for 10 seconds while the file is in use), then you can use Polly to build your retry logic.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810