如何在 C# 中读取 PDB 文件的详细信息

How to read details of a PDB file in C#

我想从 PDB 文件(在我的特定情况下是 Windows PDB 而不是便携式 PDB)中读取文档 URL(=文档的路径)等详细信息,但不能找一个简单直接的例子。

经过一些研究,我想出了以下内容,我只想分享它,因为像这样的 post 本来就是我想要的:

  1. 添加对 Microsoft.DiaSymReader.Native
  2. 的包引用
  3. 像下面这样创建一个助手 class。目前这只是读取和返回文档路径,但当然我们也可以提取其他一些细节。

重要:

  • Unsafe 项目中必须允许代码才能工作。
  • 另请注意,这些是 Windows PDB(非便携式 PDB)的步骤。
    /// <summary>
    /// Helper class to get specific contents of a PDB file.
    /// </summary>
    public static class PdbReader
    {
        /// <summary>
        /// Gets all paths of all documents from the given PDB.
        /// </summary>
        public static IReadOnlyCollection<string> GetAllDocumentPathsFromPdb(string path)
        {
            using var stream = new FileStream(path, FileMode.Open);
            var metadataProvider = new SymReaderMetadataProvider();
            var reader = SymUnmanagedReaderFactory.CreateReader<ISymUnmanagedReader5>(stream, metadataProvider);
            var result = reader.GetDocuments();

            return GetDocumentPaths(result).ToList();
        }

        private static IEnumerable<string> GetDocumentPaths(IEnumerable<ISymUnmanagedDocument> result)
        {
            foreach (var document in result)
            {
                var url = new char[256];
                document.GetUrl(url.Length, out var count, url);
                yield return new string(url, 0, count-1);
            }
        }

        /// <summary>
        /// Dummy implementation which is doing nothing.
        /// At the moment we just need it to pass *any* implementation of <see cref="ISymReaderMetadataProvider"/>
        /// to <see cref="SymUnmanagedReaderFactory.CreateReader{T}"/>.
        /// </summary>
        private class SymReaderMetadataProvider : ISymReaderMetadataProvider
        {
            public unsafe bool TryGetStandaloneSignature(int standaloneSignatureToken, out byte* signature, out int length)
            {
                throw new NotImplementedException();
            }

            public bool TryGetTypeDefinitionInfo(int typeDefinitionToken, out string namespaceName, out string typeName, out TypeAttributes attributes)
            {
                throw new NotImplementedException();
            }

            public bool TryGetTypeReferenceInfo(int typeReferenceToken, out string namespaceName, out string typeName)
            {
                throw new NotImplementedException();
            }
        }
    }

致谢:最大的帮助是 this file。谢谢 Kirill Osenkov!