C# Get path of class library

佐手、 提交于 2019-12-22 07:01:04

问题


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.


回答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



回答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".



回答3:


I don't think you can unless you start it in a new AppDomain, and that's more trouble than it's worth. Just copy the files it needs into your own project, and put them in the place it expects relative to your working directory.

(You might also want to ask the original developer why the paths to the needed files can't be given as a parameter. This would be the normal way of solving this problem.)




回答4:


I'm sure there is some functions to get the list of loaded assemblies from the ExecutingAssembly, loop across this to find you assemble(class lib) then get it's location. Sorry for vague answer.



来源:https://stackoverflow.com/questions/1762160/c-sharp-get-path-of-class-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!