/
aprogrammer
/
dotnet-docs
Обзор
Документация
Войти
/
aprogrammer
/
dotnet-docs
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
docs/standard/assembly/snippets/identify/csharp/ExamplePeReader.cs
59 строк
2 KB
MSDN.WhiteKnight
Improve How to determine if a file is an assembly (#25329)
02 авг 2021, 22:54
Не верифицирован
02 авг 2021, 22:54
5c10176
Код
Авторство
О чём код?
//<SnippetPeReader> using System; using System.Collections.Generic; using System.IO; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; static class ExamplePeReader { static bool IsAssembly(string path) { using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); // Try to read CLI metadata from the PE file. using var peReader = new PEReader(fs); if (!peReader.HasMetadata) { return false; // File does not have CLI metadata. } // Check that file has an assembly manifest. MetadataReader reader = peReader.GetMetadataReader(); return reader.IsAssembly; } public static void CheckAssembly() { string path = Path.Combine( RuntimeEnvironment.GetRuntimeDirectory(), "System.Net.dll"); try { if (IsAssembly(path)) { Console.WriteLine("Yes, the file is an assembly."); } else { Console.WriteLine("The file is not an assembly."); } } catch (BadImageFormatException) { Console.WriteLine("The file is not an executable."); } catch (FileNotFoundException) { Console.WriteLine("The file cannot be found."); } } /* Output: Yes, the file is an assembly. */ } //</SnippetPeReader>