简体   繁体   English

使用Nuget.css从csproj读取Nuget软件包

[英]Read Nuget Packages from csproj with Nuget.Packages

I have a console application that scans for duplicate or out of date nuget packages. 我有一个控制台应用程序,可以扫描重复的或过期的nuget软件包。 When the packages were located in packages.config I could use this code 当软件包位于packages.config中时,我可以使用此代码

var packageReferences = new PackagesConfigReader(
                    new FileStream(path, FileMode.Open, FileAccess.Read))
                    .GetPackages();
 return packageReferences;

To read them and get back IEnumerabla. 要阅读它们并取回IEnumerabla。 I'm trying to make it work with CSPROJ files, but the above does not work any more, and I can't seem to find any documentation on how to read it (other than manually loading the XML). 我正在尝试使其与CSPROJ文件一起使用,但是以上内容不再起作用,而且我似乎找不到任何有关如何读取文件的文档(除了手动加载XML外)。

Is there a way to make it work with CSPROJ files ? 有没有办法使其与CSPROJ文件一起使用?

I suggest parsing the XML. 我建议解析XML。 I created this in two minutes. 我在两分钟内创建了这个。

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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM