Implicit base directory of Windows vs Linux

I know that this isn’t actually a MonoGame related question and is more about .NET, but I’m sure others using MonoGame have encountered this before.

On Windows, relative paths have their base directory as the folder that contains the executable. So if I have a project at C:\Code\ProjectName\ProjectName, a path such as “Example1” will expand to C:\Code\ProjectName\ProjectName\bin\Debug\Example1.

On Linux, however, the behavior seems to be different. The path will instead expand to "home\Code\ProjectName\ProjectName\Example1.

Why is the behavior different, and what’s the best way to get around that?

Fwiw, in my game, I used the following code to get the directory that contains the executable:

	public static string GetExecutablePath()
	{
		string executablePath = Process.GetCurrentProcess().MainModule.FileName;
		DirectoryInfo executableDirectory = Directory.GetParent(executablePath);

		return executableDirectory.FullName;
	}

Some things to note:

  • Using . doesn’t technically work because the current working directory may or may not be the same as the location of the executable. For instance, if I were in a/b/c and I invoked ~\d\e\f\myMonoGame.exe, then the current working directory would be a/b/c (which has nothing to do with the location of my executable).
  • I had previously used System.Reflection.Assembly.GetExecutingAssembly().Location but it didn’t work well in certain cases – specifically, when using PublishSingleFile. c# - Cannot get original executable path for .net core 3.0 single file '/p:PublishSingleFile=true' - Stack Overflow notes this, and also contains other code solutions.
1 Like

Thanks for the reply. I actually figured out why I was getting different behavior between my Visual Studio coding environment on Windows and VS Code on Linux: in the process of translating my Windows code to Linux compatible code, evidently a launch.json file was auto-generated that specified the “cwd” (presumably stands for “current working directory”) when debugging, and it wasn’t the folder where the binaries were being placed.

It remains to be seen whether the unqualified paths will work as expected when I’ve built the game for publishing and moved all the files to their own directory not attached to a code project. If I encounter unexpected behavior there, I may have to explicitly determine the game directory in code using something like what you’re doing.

1 Like