user3783611
user3783611

Reputation: 1

Read NuSpec from NuPkg

I have been looking around and trying to see if it's possible to read the NuSpec file from a Nuget package with VB.NET. Essentially, I retrieve a NuGet package, but would like to get its version and ID programatically from the NuSpec before doing anything with it.

Upvotes: 0

Views: 390

Answers (1)

thatguy
thatguy

Reputation: 22089

You do not need the NuSpec file for that. The ID and version are already contained in the file name, e.g. System.Runtime.CompilerServices.Unsafe.4.7.1.nupkg. So if you have the package file, you can read its full name and use the following regex pattern to match it with Regex.

^(?<PackageName>.*?)\.(?<PackageVersion>(?:\.?[0-9]+){3,}(?:[-.\w]+)?)\.nupkg$

The regex contains two named groups, one for the package name and one for the package version, so you can easily get them from the Match return by Regex.Match.

Dim input As String = "System.Runtime.CompilerServices.Unsafe.4.7.1.nupkg"
Dim pattern As String = "^(?<PackageName>.*?)\.(?<PackageVersion>(?:\.?[0-9]+){3,}(?:[-.\w]+)?)\.nupkg$"
Dim match As Match = Regex.Match(input, pattern)

As you change the name of the NuSpec file, you can alternatively load the file as XML document and extract the ID and version from it like below.

Dim nuSpecFilePath = "C:\Users\benjamin\Desktop\Test\Grpc.Core.nuspec"

Using file = New FileStream(nuSpecFilePath, FileMode.Open)
   Dim xmlReader = New XmlTextReader(file) With { Namespaces = False }
   Dim xmlDocument = New XmlDocument()

   xmlDocument.Load(xmlReader)

   Dim id = xmlDocument.SelectSingleNode("package/metadata/id").InnerText
   Dim version = xmlDocument.SelectSingleNode("package/metadata/version").InnerText
End Using

As a note, opening a file stream and creating the XML reader by hand with Namespaces = False is just a way to ignore the XML namespace, that you would have to specify explicitly otherwise and it may vary in different versions of NuSpec.

Upvotes: 1

Related Questions