简体   繁体   English

在 Visual Studio 中获取文件的内容而无需从扩展中打开文件

[英]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.我正在尝试读取 Visual Studio 扩展中文件的内容。 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).或者,获取项目项的路径(然后我可以只使用 System.IO 来访问文件内容)。

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.您可以通过读取ProjectItem的属性来获取它的路径。

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

After you have the path you can read its content with System.IO .获得path您可以使用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.如果文件有点大,并且由于大小而导致当前代码出现问题,则应查看StreamReader类。

I'm not sure if this is possible for extensions but you could probably use System.IO , like this:我不确定这是否可以用于扩展,但您可能可以使用System.IO ,如下所示:

using System.IO;

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

You could also use StreamReader like this:您还可以像这样使用StreamReader

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).我会尝试手动搜索 SDK 文件(或使用文件爬虫)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM