Diego Alves
Diego Alves

Reputation: 2677

Access to path is denied, Asp.net core 2.0 running on Ubuntu

I am not able to use the bellow line of code. On my development machine (Windows) it is working. Yes, I am developing the application on Windows and deploying on Ubuntu. The next application I won't do this.

I got the error message "access to the path /var/... is defined".

try
{
   Directory.CreateDirectory(dirInfo.FullName + "/" + numDirs);
}
catch(Exception e)
{
   return e.Message; // access to the path /var/... is defined
}

I am using nginx as proxy server for Kestrel. As described in the Microsoft guide

I tried to fire some permission commands randomly, as I am far from being an expert on Ubuntu but the CreateDirectory method is still generating error.

the permission commands I've tried:

sudo chown -R www-data:www-data /var/www/PROJECTDIR

sudo find /var/PROJECTDIR -type d -exec chmod 770 {} \;
sudo find /var/PROJECTDIR -type f -exec chmod 660 {} \;

I am not setting my project inside /var/www I am using something like /var/anotherdir/anotherdir, is it a issue?

Upvotes: 1

Views: 3949

Answers (1)

Diego Alves
Diego Alves

Reputation: 2677

Actually what was thowing the exception was my extension method of IFormFile. I try to post as little code as I can to make the question more compact but I think it is not a good idea anymore, I should have posted the try catch blocks as they are in my project. In my code I had something like this. obs. I am only testing, in the end I get rid of the literals and excessive variable references.

    try
{
   Directory.CreateDirectory(dirInfo.FullName + "/" + numDirs);
   file.SaveAs(dirInfo.FullName + "/" + numDirs) // it was this that threw the exception.
}
catch(Exception e)
{
   return e.Message; // access to the path /var/... is defined
}

That was one of the most anoying errors I ever had. Fortuantely I encountered an exact problem in this post that solved my problem. I was passing just the directory.

Somehow on Windows it works but on Linux doesn't.

 public static void SaveAs(this IFormFile formFile, string filePath)
{
    using (var stream = new FileStream( filePath, FileMode.Create))
    {
        formFile.CopyTo(stream);
    }

}

The solution:

 public static void SaveAs(this IFormFile formFile, string filePath)
    {
        using (var stream = new FileStream( Path.Combine( filePath, formFile.FileName), FileMode.Create))
        {
            formFile.CopyTo(stream);
        }
    }

Upvotes: 0

Related Questions