I'm working on a project, and we need to know the version of a NuGet package we are using, and use it in the code.
One way I tried was to read from the packages.config
file, parse it for the package I want, and parse the line for the version. Something like:
var lines = System.IO.File.ReadAllLines(@"..\..\packages.config");
foreach(var line in lines)
{
if (line.Contains("My.Package"))
{
foreach(var part in line.split(' '))
{
if (part.Contains("version"))
{
return part.Split('"')[1];
}
}
}
}
Is there a better way to do this programmatically?
Note: The above code will not work, as packages.config is not deployed with the application.
If the package has any classes you can just get the assembly from that class and then the version. However, if the package has no classes, e.g. does something like copying files using nuget.targets then it's impossible this way.
Console.WriteLine("Using Selenium.WebDriver: " + Assembly.GetAssembly(typeof(OpenQA.Selenium.By)).GetName().Version.ToString());
Good question. But you have not said why you want to know the version.
I have to start my answer from pointing that you're on the wrong path. I suspect that you need to know at runtime the version of assembly in use.
But the whole NuGet concept and packages.config
is a compile-time concept and not a runtime concept. You shouldn't even have packages.config
in your output folder or published folder. At runtime you need to get loaded assemblies from AppDomain.CurrentDomain
. I will not go in depth on it here, but here is the reference you can look at. I only say that you can get assembly version there.
Then, in code, if you want to do things differently based on certain assembly version. If you want to compile based on version of framework or assembly - check this post
Bottom Line:
The fact that packages.config exist or not, or what it has in it, has no correlation to which DLL file has been used at compile time. VS has an incredible ability to crawl through directories and finding matching DLL files. packages.config can be outdated or desynchronized with the actual dll. This is not a bullet-proof way to do things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With