0

I am trying to generate an assembly file (Dll) from current active document in the editor.

Ex. I have 3 C# source files - file1.cs, file2.cs, file3.cs and if I currently opened the file2.cs in the editor. I need to build an assembly Dll only for a single file file2.dll using the Roslyn compiler API.

  • You generally can't do that. (what if the files depend on eachother? What references / project settings / build steps?) – SLaks Sep 07 '16 at 19:09
  • Generally this will not work unless the class is completely self contained. – Paul Swetz Sep 08 '16 at 14:17
  • thanks, if I can use Roslyn API - CSharpCompilation and link all the references this source uses while creating the compilation unit? – Hanif Zubair Sep 09 '16 at 00:43

3 Answers3

0

You can get the current document text with the following code:

EnvDTE.TextDocument textDocument = (EnvDTE.TextDocument)DTE.ActiveDocument.Object("TextDocument");
EnvDTE.EditPoint editPoint = textDocument.StartPoint.CreateEditPoint();
string result = editPoint.GetText(textDocument.EndPoint);
Sergey Vlasov
  • 26,641
  • 3
  • 64
  • 66
0

Ignoring the concerns about "that might not work" for a moment, rather than getting the text, get the actual syntax tree from the Roslyn API and then construct your compilation with that. You can either get it from the VisualStudioWorkspace or other places. That means you don't have to reparse the file yourself, which is potentially tricky if the user has #if directives and other stuff. You can also get the SourceText from the workspace API as well, which you can directly hand back to our parser if you do need to reparse, but that'll be a lot more efficient than reconstructing a string.

Jason Malinowski
  • 18,148
  • 1
  • 38
  • 55
0
DTE2 dte2 = Package.GetGlobalService(typeof(DTE)) as DTE2;
   
Document active = dte2.ActiveDocument;
TextDocument textDocument = (TextDocument)dte2.ActiveDocument.Object();

EditPoint endPoint = textDocument.EndPoint.CreateEditPoint();
string content = endPoint.GetLines(1, textDocument.EndPoint.Line + 1);
osynavets
  • 1,199
  • 1
  • 12
  • 22