1

I'm new to Visual Studio extensions. I'm developing a Menu Command extension to add a using directive to my class. So far, I could successfully create a new Document object containing the changes:

    var syntaxTree = await sourceDocument.GetSyntaxTreeAsync();
    var unitRoot = syntaxTree.GetCompilationUnitRoot();
    var qualifiedName = SyntaxFactory.ParseName("MyApp.Utilities"); // using MayApp.Utilities
    var usingDirective = SyntaxFactory.UsingDirective(qualifiedName);
    unitRoot = unitRoot.AddUsings(usingDirective);
    var newDocument = sourceDocument.WithSyntaxRoot(unitRoot);

The problem is it doesn't reflect the changes back to the source code (or workspace if it's correct term).

Any idea and suggestion is appreciated.

Hans
  • 2,674
  • 4
  • 25
  • 48
  • It will not do that because you don't apply a `newDocument` to workspace which gave you the original `sourceDocument`. – George Alexandria Sep 30 '18 at 11:03
  • @GeorgeAlexandria Would you please teach me (or direct me to right sample/reference) how to do that? – Hans Sep 30 '18 at 11:08
  • As one of examples, you can look at [this question](https://stackoverflow.com/questions/35896780/change-files-using-roslyn) or can find something help in the @JoshVarity [blog](https://joshvarty.com/2014/09/12/learn-roslyn-now-part-6-working-with-workspaces/) – George Alexandria Sep 30 '18 at 11:30
  • You may find this [this question](https://stackoverflow.com/questions/37710714/roslyn-add-new-method-to-an-existing-class) interesting, since it specifically tags visual-studio-extensions. – Phil Jollans Jan 13 '19 at 17:57

0 Answers0