简体   繁体   中英

Insert Assembly Attributes into AssemblyInfo.cs

I'm trying to figure out how to use rosyln to insert assembly attributes into AssemblyInfo.cs .

My attributes look something like this:

[assembly: Foo(@"\\somepath\tosomething)"]

And I can read them like this:

var syntaxRoot = tree.GetRoot();

var attr = syntaxRoot.DescendantNodes().OfType<AttributeSyntax>(); 
var attrNames = attr.Select(a => a.Name);
var deployments = attr.Where(a => a.Name.ToString() == "Foo")
    .Select(d => d.DescendantTokens()
    .FirstOrDefault(t => t.Kind() == SyntaxKind.StringLiteralToken).ValueText);

And I can get the argument that was passed to the attribute.

I can try to insert an attribute like so:

var list = new List<SyntaxNode>()
{
    SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList<AttributeSyntax>(new List<AttributeSyntax>()
    {
        SyntaxFactory.Attribute(SyntaxFactory.ParseName("DeploymentLocation"))
    }))
};
var n = tree.GetRoot().InsertNodesAfter(tree.GetRoot().ChildNodes().Last(), list);

This will insert a node that ends up looking something like this:

...
[assembly: AssemblyFileVersion("1.0.0.0")]
[DeploymentLocation]

So it's added my attribute, but it doesn't have the assembly: prefix and I can't figure out how to get the string literal arguments in there.

I know I could (and probably should) just load the file and use a simple text writer to insert strings, but in the interests of understanding how Roslyn is supposed to work.

Pasting the code into Roslyn Quoter shows

    .WithTarget(
        AttributeTargetSpecifier(
            Token(SyntaxKind.AssemblyKeyword)))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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