In my experience, executing .NET code from MS Access seems to have "messed up" some of the .NET methods "get the current directory", which all work fine if you run the same .NET application directly without Access.
If you want to know what I'm talking about, create a new console application in Visual Studio and paste the following code:
using System; using System.IO; namespace CurrentDirTest { class Program { static void Main(string[] args) { Console.WriteLine(Environment.CurrentDirectory); Console.WriteLine(Directory.GetCurrentDirectory()); Console.WriteLine(System.Threading.Thread.GetDomain().BaseDirectory); Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory); Console.ReadLine(); } } }
When I run this directly from Visual Studio, it outputs this (as expected):
C: \ Dev \ Code \ CurrentDirTest \ CurrentDirTest \ Bin \ Debug C: \ Dev \ Code \ CurrentDirTest \ CurrentDirTest \ Bin \ Debug C: \ Dev \ Code \ CurrentDirTest \ CurrentDirTest \ Bin \ Debug \ C: \ Dev \ Code \ CurrentDirTest \ CurrentDirTest \ Bin \ Debug \
Now put the compiled .exe file in the Program Files (x86)\mytool\
and try to call it from Access with the VBA code from your question.
When I do this on my machine, I get the following:
C: \ Users \ MyUserName \ Documents
C: \ Users \ MyUserName \ Documents
C: \ Program Files (x86) \ mytool \
C: \ Program Files (x86) \ mytool \
Strange, isn't it? Environment.CurrentDirectory
and Directory.GetCurrentDirectory()
both return my Documents folder as soon as the application runs from MS Access.
I have no idea why this is happening, but it is.
Decision:
If you get the same results on your computer as I do, my solution is very simple: just use System.Threading.Thread.GetDomain().BaseDirectory
or AppDomain.CurrentDomain.BaseDirectory
to get the current directory.
Just in case, someone has a similar problem when using COM-Interop: The problem is even worse when you build .NET through COM-Interop from MS Access.
If I remember him correctly, both System.Threading.Thread.GetDomain().BaseDirectory
and AppDomain.CurrentDomain.BaseDirectory
did not work for me either because both returned the msaccess.exe
directory.
I had to use this.GetType().Assembly.Location
to get the actual location of the .NET assembly.