在 Visual Studio 擴充功能中使用檔案和文件
以下是使用檔案和文件之不同方式的小型程式碼範例集合。
取得使用中文字檢視
取得目前使用中文字檢視,以操作其文字緩衝區文字。
DocumentView docView = await VS.Documents.GetActiveDocumentViewAsync();
if (docView?.TextView == null) return; //not a text window
SnapshotPoint position = docView.TextView.Caret.Position.BufferPosition;
docView.TextBuffer?.Insert(position, "some text"); // Inserts text at the caret
檔案圖示關聯
若要將圖示與 [方案總管] 中的副檔名產生關聯,請將 [ProvideFileIcon()]
屬性新增至套件類別。
[ProvideFileIcon(".abc", "KnownMonikers.Reference")]
public sealed class MyPackage : ToolkitPackage
{
...
}
使用 KnownMonikers Explorer 工具視窗查看 KnownMonikers
集合中的數千個可用圖示。 在主功能表的檢視>其他視窗下尋找它。
開啟檔案
使用 Microsoft.VisualStudio.Shell.VsShellUtilities
協助程式類別。
string fileName = "c:\\file.txt";
await VS.Document.OpenAsync(fileName);
透過專案開啟檔案
當您開啟的檔案是解決方案的一部分時,請使用這個方法。
string fileName = "c:\\file.txt";
await VS.Documents.OpenViaProjectAsync(fileName);
在 [預覽] 索引標籤開啟檔案
[預覽] 索引標籤也稱為 [暫存] 索引標籤,是文件區域右側開啟的暫時索引標籤。 在 [預覽] 索引標籤中開啟任何檔案,如下所示:
string fileName = "c:\\file.txt";
await VS.Documents.OpenInPreviewTabAsync(fileName);
從 ITextBuffer 取得檔名
使用buffer.GetFileName()
位於Microsoft.VisualStudio.Text
命名空間中的擴充方法。
string fileName = buffer.GetFileName();
來自於檔案的 SolutionItem
從絕對檔案路徑尋找 SolutionItem
。
string fileName = "c:\\file.txt";
PhysicalFile item = await PhysicalFile.FromFileAsync(fileName);