Arnold Zahrneinder
Arnold Zahrneinder

Reputation: 5200

Directory creation and concurrency

When requiring to create a folder in an action API, would there be any concurrency issue involved? If so, would the proper solution be to use a lock as in the following code

public async Task<IActionResult> UploadFile(User user){
     ...
     var file = HttpContext.Request.Form.File["SomeFile"];
     ...
     var path = Path.Combile(hostingEnvironment.WebRoot, configurationRoot["BaseDirectory"], user.Id);
     lock(path){
         if(!Directory.Exists(path)){
             Directory.CreateDirectory (path);
         }
     }
     ...
}

Would it be also logical to use the path variable as the lock object?

Upvotes: 0

Views: 352

Answers (1)

mjwills
mjwills

Reputation: 23975

Just call Directory.CreateDirectory and don't stress about concurrency.

From the docs ( https://msdn.microsoft.com/en-us/library/54a0at6s(v=vs.110).aspx ) :

If the directory already exists, this method does not create a new directory, but it returns a DirectoryInfo object for the existing directory.

Upvotes: 5

Related Questions