我有一个控制台应用程序,可以扫描重复或过期的nuget程序包。当软件包位于packages.config中时,我可以使用此代码
var packageReferences = new PackagesConfigReader(
new FileStream(path, FileMode.Open, FileAccess.Read))
.GetPackages();
return packageReferences;
阅读它们并返回IEnumerabla。我正在尝试使其与CSPROJ文件一起使用,但以上内容不再起作用,而且似乎找不到有关如何读取它的任何文档(除了手动加载XML)。
有没有办法使它与CSPROJ文件一起使用?
答案 0 :(得分:1)
我建议解析XML。我在两分钟内创建了这个。
void Main()
{
var xml = @"<Project Sdk=""Microsoft.NET.Sdk.Web"">
<PropertyGroup>
<TargetFramework>net47</TargetFramework>
<OutputType>Exe</OutputType>
<GenerateAssemblyTitleAttribute>true</GenerateAssemblyTitleAttribute>
<GenerateAssemblyDescriptionAttribute>true</GenerateAssemblyDescriptionAttribute>
</PropertyGroup>
<ItemGroup>
<PackageReference Include=""Microsoft.AspNetCore"" Version=""2.1.2"" />
<PackageReference Include=""Microsoft.AspNetCore.Authentication.Cookies"" Version=""2.1.1"" />
<PackageReference Include=""Microsoft.AspNetCore.Authentication.JwtBearer"" Version=""2.1.1"" />
</ItemGroup>
</Project>";
var doc = XDocument.Parse(xml);
var packageReferences = doc.XPathSelectElements("//PackageReference")
.Select(pr => new PackageReference
{
Include = pr.Attribute("Include").Value,
Version = new Version(pr.Attribute("Version").Value)
});
Console.WriteLine($"Project file contains {packageReferences.Count()} package references:");
foreach (var packageReference in packageReferences)
{
Console.WriteLine($"{packageReference.Include}, version {packageReference.Version}");
}
// Output:
// Project file contains 3 package references:
// Microsoft.AspNetCore, version 2.1.2
// Microsoft.AspNetCore.Authentication.Cookies, version 2.1.1
// Microsoft.AspNetCore.Authentication.JwtBearer, version 2.1.1
}
public class PackageReference
{
public string Include { get; set; }
public Version Version { get; set; }
}