How to solve Access to the path is denied Error in C#.NET Core application

Prabs 1 Reputation point

Hi Team,

I have an C#.Net core 3.1 console application which is running on RedHat Linux.
I have to create a file in the following path in Linux OS using C#.Net Core.


When i run at root user, the file is created succcessfully.
But when i run at normal user, the file is not created and giving following exception in Linux machine

Access to the path "var/log/TEST_LOG/" is denied.

Please help me on this issue.
My requirement is application has to run at normal user not root user.

Please find the following code,

static void CreateLogs()

        string linux_path = "";            
        linux_path = @"var/log/TEST_LOG/";                   

            string directoryPath = Path.Combine("/", linux_path);

            if (!Directory.Exists(directoryPath))
                Console.WriteLine("Directory path created " + directoryPath);

            string filePath = directoryPath + "EventLog.txt";

            Console.WriteLine("file path " + filePath);

            FileStream m_LogFile = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);

            using (StreamWriter m_LogFileWriter = new StreamWriter(m_LogFile, Encoding.UTF8))
                m_LogFileWriter.WriteLine("This file contains C#.");

        catch (Exception exp)
            Console.WriteLine(exp.Message + " " + exp.StackTrace);
A cross-platform toolchain for developing, building, running, and publishing .NET applications.
299 questions
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,983 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: The period of time during which a program is being executed in a computer.
1,043 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 41,766 Reputation points

    By default only the root user can write to var. This is by design and your app cannot change that.


    1. As part of your app installation, while root, create the var/log folder and give whatever user(s) need to run your app write permissions to the directory
    2. Pick a different directory that your user would have write permissions to
    3. (Not a good idea) Have the root user give write access to the var folder to the user running your app
    0 comments No comments

  2. Carsten Riedel 11 Reputation points

    Hi this guide should help.,group%20access%20to%20that%20directory.%20Weitere%20Artikel...%20

    The guide describes , add user to group , assign group to directory. (Read/Edit)

    I would personally choose and other directory like /var/lib/appname/logs.

    0 comments No comments