0

I created a program (C#) that use a data base file for work.

I used a string to represents the path of this file (returned by the Path.GetDirectoryName() function) and worked before I published with Visual Studio.

So I tested the executable file generated by the publish method, unfortunately, doesn't work. I investigated the problem and I discovered that this function (Path.GetDirectoryName()) returned a null value for my string path. Why this function works before the publish method and doesn't after?

The block of code that I tried:

    public class CargaDao 
    {
        static private string caminhoDoBanco = "";

        public void inicializarBanco()
        {
            string diretorioBase = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            caminhoDoBanco = Path.Combine(diretorioBase, "Gollog.db");
        }
    }
// there is more methods of course but is not relevant for the moment.

but the string, like I said, get a null value.

This problem generated other problems like an error when I use Path.Combine() because my string is passed for this function.

6
  • Are you publishing it as 1 output file? I've read about dynamic loaded assemblies don't have an Assembly.Location. I don't know if these are two different things. but might be related? Commented Jan 19, 2024 at 22:26
  • If Path.GetDirectoryName() is returning null, what are you passing into it? dotnetfiddle.net/TKQG8B Commented Jan 19, 2024 at 22:28
  • Side note: the database file shouldn't be in the same folder as the executable. Use the SpecialFolders enumeration to determine a more suitable location. See Get Special Folder Commented Jan 19, 2024 at 22:46
  • When you publish are you using Single-file deployment? From the Remarks for Assembly.Location Property: "In .NET 5 and later versions, for bundled assemblies, the value returned is an empty string." Commented Jan 19, 2024 at 23:22
  • 1
    @JonathanDodds Yes, That's the source of the problem! Thank you! Commented Jan 20, 2024 at 20:18

1 Answer 1

1

As said before in the comments, the problem is because the Single-file deployment make the Assembly.Location returns an empty string in .NET 5 and later versions. You can try another methods to get the current absolute path of your executable file.

Unfortunately, i don't see a solution to dependencies that use the Assembly.Location without changing them. If that's your case, you might consider changing the deployment method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.