C# Get path of class library

17,921

Solution 1

I know this is an old post but in the event someone else stumbles on it from a search, the easiest way I've found to do this is:

Public Class Foo

     Public Shared Function GetMyPath() As String
          Return Path.GetDirectoryName(GetType(Foo).Assembly.Location)
     End Function

End Class

Solution 2

This is happening because your startup project has two options as to loading the library

  1. Copy it to it's own folder (what would cause the behaviour you are experimenting)
  2. Load it from GAC (what would make impossible to load any XML from it's folder)

So you have two options here:

  1. Import the XML files in the project and embed them as "embedded resources" in the class library and load it in memory at runtime
  2. Import the XML files in the project and change the "copy to output directory" property of the file to "true".
Share:
17,921
djskinner
Author by

djskinner

Updated on June 04, 2022

Comments

  • djskinner
    djskinner almost 2 years

    I have a class library that uses some xml files found in its own directory.

    When referencing this library from another project, how do I ensure the library is working from it's own directory?

    I tried Assembly.GetExecutingAssembly().Location but that still returns the path of the startup project.

  • djskinner
    djskinner over 14 years
    I am the original developer so this might be an option but I don't want to have to keep a seperate copy of the same xml files for each project that uses the library.
  • djskinner
    djskinner over 14 years
    Point 2 worked. However, it doesn't seem an ideal solution since there could be clashes. The reason it wasn't working before is because I also had a Data directory in another referenced project.
  • Andre Pena
    Andre Pena over 14 years
    Use option 1 instead so.. but application users won't be able to edit the XMLs. I can't see other options.
  • Can Sahin
    Can Sahin over 14 years
    To add another options: Put the XML files into some designated data directory and store that directory path in your app.config. After you, you will deploy your project to other PCs and use it outside of Visual Studio, won't you?
  • Leif
    Leif over 11 years
    @iamserious: Are you serious?
  • iamserious
    iamserious over 11 years
    @Leif, hahaha, I don't remember making this (silly) comment; very possibly was drunk when I made this.