Lightpower Lightpower - 1 year ago 136
Linux Question

Mono executes program with wrong current directory

I have a strange problem. I have written a custom spamfilter in C# .NET 4.6 for personal use. And I put this program up to my Raspberry Pi.

I have tested many times the program, and everything worked fine, but when I created a cronjob I have noticed that the program never writes log.

As I started to test again I have find out, that the problem is, when I start the program from the program's base dir, it works fine:

> cd path/to/program
> mono program.exe

but when I start it from another directory with absolute path:

> mono /absolute/path/to/program/program.exe

The required files' relative paths go wrong.

For example if I'm in the /home directory, and my program is in /home/user/program directory, and I run this:

> mono /home/user/program/program.exe

I get " Could not find file "/home/xyz.txt" "

I have tried to create absolute paths from relative paths in the program using
but nothing changed.

So my question is: Is there any option to run a mono program in another directory with correct current directory?

I know that a bash script could execute my first solution (cd and then mono) and it could be used in cron, but I want to know if there is a simplier solution.

Answer Source

The current directory is correct, it is the current directory of where you are starting the process, and that process is mono in this case, and not the location of the CIL-based assembly that mono is loading.

What is sounds like you want is the path of the ExecutingAssembly.

This works on x-plat (Windows/Linux/macOS):

string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download