Write txt file in linux for .net Core (Docker)

Viewed 2768

I am new in Linux and my API was created in .net core and running in Docker. The system i create will write/create a txt file that will input all errors logged in the API. My code to write is this

`public class WriteLogs {

    public void ErrorLogFile(string traceNo, string errorMsg)
    {
        DirectoryInfo dir = new DirectoryInfo(Startup.errorPath);
        if (!dir.Exists)
        {
            dir.Create();
        }

        using (StreamWriter swLog = File.AppendText(Startup.errorPath + Startup.errorFileName + DateTime.Now.ToString("MMddyyyy") + ".txt"))
        {
            swLog.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff") + " - Trace Number : " + traceNo + "   " + errorMsg + "\n");
        }
    }
}`

the value in my startup is located in my appSettings.json file :

"ErrorPath": "C:\\BP\\", "ErrorFileName": "BP-ParamLogs_",

This is working in windows environment but when i transfer my program to linux and change the ErrorPath to:

"ErrorPath": "/home/Logs/",

the file was not created.

My question is, do my syntax works in linux to write txt file or my path was wrong?

2 Answers

To answer your specific question about the syntax. \home\Logs\ should be /home/Logs/ as Linux uses forward-slash for path separator.

There's a chance that your program does not have write access to the /home/ directory. I've personally tried a similar program and I ran into System.UnauthorizedAccessException during the logs directory creation step.

Try running your program from the terminal with dotnet run to see the exception you might be getting. If you are also running into the System.UnauthorizedAccessException then run as root with sudo dotnet run

i just solved the problem by using command:

find . -name BP-Param*

from the first directory. After executing it. it was in the docker directory.

Related