why to I get this error: System.UnauthorizedAccessException: 'C:\Windows\system32\CSV_file'

403 Views Asked by At

I have written a code in C#. The code is loging into a file the following:

  1. CPU Usage
  2. RAM Usage
  3. Network card traffic
  4. Current time

I want that on system startup the code will be executed automatically. So I have written a batch file that runs the .exe file like that:

START 'C:\Debug\DiagnisticTool.exe'

while DiagnisticTool.exe is the application and it is contained in a folder named 'Debug' at C drive. The batch file is in the windows startup folder.

While I start my PC the batch file is running and than the error stated above comes up. This is how the file is been written in the script code:

using (StreamWriter outputFile = File.AppendText("PerformanceLogFile.csv"))
                {
                    outputFile.WriteLine(something to write to file);
                }

yet the error stateds that it tries to write it somewere else: 'C:\Windows\system32'.

Why is that?

When I run the program via visual studio or via the .exe application that it created it is runing OK. Plus when I run the batch file manually it works fine. The ONLY problem is that it doesn't run at startup as it should.

1

There are 1 best solutions below

5
Steve On BEST ANSWER

This happens because when your program is called by the batch the current folder is not the one you have your executable and windows doesn't care to change the current directory to your folder. The only thing that matters is the availability of your program and this is granted because you give the full path to the START command.

You can fix your problem changing the START command and specifying the folder where your program should be run

START /D C:\Debug C:\Debug\DiagnisticTool.exe

or adding a CD command just before running the file

CD C:\DEBUG
START C:\DEBUG\DiagnosticTool.exe

or changing the path passed to StreamWriter

using (StreamWriter outputFile = File.AppendText(@"C:\debug\PerformanceLogFile.csv"))

this last option, while allowing to leave your batch as is, could be a problem if you want to customize the output folder. For example if you are not allowed to create a C:\DEBUG folder on the target machine or for some other reason.