共用方式為


在 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 取得檔案名稱

使用命名空間中的Microsoft.VisualStudio.Text內的buffer.GetFileName()擴充方法。

string fileName = buffer.GetFileName();

檔案中的 SolutionItem

從絕對檔案路徑中尋找SolutionItem

string fileName = "c:\\file.txt";
PhysicalFile item = await PhysicalFile.FromFileAsync(fileName);