I assign new json text to a document using the following code:
public virtual async Task SetDocumentText(FileInfo fileInfo, string contents)
{
if (fileInfo == null)
throw new ArgumentNullException(nameof(fileInfo));
var projectItem = FindDTEProjectItem(fileInfo.FullName);
if (null == projectItem?.Document)
await Task.Run(() => fileInfo.WriteAllText(contents));
else
{
var textSelection = (TextSelection)projectItem.Document.Selection;
textSelection.SelectAll();
textSelection.Text = contents;
projectItem.Document.Save();
}
}
But I have three problems with the current solution:
Is there a better way to assign the new text to the EnvDTE.Document?
This is what the corrupted text looks like:
But this is what I assigned:
...
...
},
"client": {
"title": "Mr"
}
}
The json text that I assigned is valid and well-formed, and even if it wasn't, I wouldn't expect such a drastic corruption of the json text.
If I write the text directly to the file, then Visual Studio will ask the user whether he wants to reload, and I am trying to avoid that popup too.
Any help would be appreciated. I was unsuccessful in using roslyn and the TextDocument because I am unable to load the AdditionalDocument. Only code files are included in the roslyn Project Documents collection.
Instead of textSelection.Text = contents;
you can use textSelection.Insert(contents);
. It is faster and prevents Visual Studio from changing the original contents.