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 Path.GetFullPath()
and Environment.CurrentDirectory
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.
Advertisement
Answer
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 it 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); Console.WriteLine(path);