简体   繁体   中英

Getting the contents of a file in Visual Studio without opening the file from an extension

I'm trying to read the contents of a file in a Visual Studio extension. The following code works, but forces me to open the file, if it isn't (otherwise it crashes):

textDocument = (TextDocument)projectItem.Document.Object("TextDocument");    
EditPoint editPoint = textDocument.StartPoint.CreateEditPoint();
string text =  editPoint.GetText(textDocument.EndPoint);

I can get the path of the project, so I suppose I could make an educated guess as to the location of the project item. However, ideally I'd like to either get the file contents without opening it; or, alternatively, get the path to the project item (then I could just use System.IO to access the file contents).

I've looked, but don't seem to be able to find any mention of either of these. Can anyone point me in the right direction, please?

You can get the path from a ProjectItem by reading its properties.

var path = YourProjectItem.Properties.Item("FullPath").Value.ToString()

After you have the path you can read its content with System.IO .

string content = File.ReadAllText(path);

If the file is somewhat larger and you are getting troubles with the current code due to size, you should take a look at the StreamReader class.

I'm not sure if this is possible for extensions but you could probably use System.IO , like this:

using System.IO;

string filePath = @"C:\Whatever\YourFileName.txt";
string fileText = File.ReadAllText(filePath);

You could also use StreamReader like this:

using System.IO;

string filePath = @"C:\Whatever\YourFileName.txt";
using (StreamReader sr = new StreamReader(filePath))
    fileText = sr.ReadToEnd();

EDIT:

I think I understand you better now.

The only way to "get the file contents without opening it" would be if the extension were to give you that data actively, but I can safely assume it doesn't.

When reading a file, you should already know where the file is (if you don't know then either you're not intended to access that file or you just haven't looked long enough).

I'd try searching the SDK files manually (Or with a file crawler).

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