I'm trying to write a tool to remove all the unused using statements from a C# document via Rosyln. There are some links on here to solutions, but they are all out of date and none of them work (as in, won't even compile.)
I can find the list of using statements easily enough:
async Task<List<UsingDirectiveSyntax>> GetExistingUsings(Document document)
{
var root = await document.GetSyntaxRootAsync();
var compilationUnit = root as CompilationUnitSyntax;
if(compilationUnit == null)
return new List<UsingDirectiveSyntax>();
var oldUsings = compilationUnit.Usings.ToList();
return oldUsings;
}
But I'm not sure how to search the document to find all the types that are used, or, once done, how to write the using lines back into the existing document to save it.
I can probably do this by reading the generated DLL with reflection, and doing some hacks to the text of the document, but that doesn't seem to be the right way to do it; surely Roslyn can do this?
Any pointers you might offer?