-
Notifications
You must be signed in to change notification settings - Fork 566
Expand file tree
/
Copy pathMetadataResolver.cs
More file actions
65 lines (59 loc) · 1.79 KB
/
MetadataResolver.cs
File metadata and controls
65 lines (59 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
namespace Xamarin.Android.Tasks
{
/// <summary>
/// A replacement for DirectoryAssemblyResolver, using System.Reflection.Metadata
/// </summary>
public class MetadataResolver : IDisposable
{
readonly Dictionary<string, PEReader> cache = new Dictionary<string, PEReader> ();
readonly List<string> searchDirectories = new List<string> ();
public MetadataReader GetAssemblyReader (string assemblyName)
{
var assemblyPath = Resolve (assemblyName);
if (!cache.TryGetValue (assemblyPath, out PEReader reader)) {
reader = new PEReader (File.OpenRead (assemblyPath));
if (!reader.HasMetadata) {
reader.Dispose ();
throw new InvalidOperationException ($"Assembly '{assemblyPath}' is not a .NET assembly.");
}
cache.Add (assemblyPath, reader);
}
return reader.GetMetadataReader ();
}
public void AddSearchDirectory (string directory)
{
directory = Path.GetFullPath (directory);
if (!searchDirectories.Contains (directory))
searchDirectories.Add (directory);
}
public string Resolve (string assemblyName)
{
string assemblyPath = assemblyName;
if (!assemblyPath.EndsWith (".dll", StringComparison.OrdinalIgnoreCase)) {
assemblyPath += ".dll";
}
if (File.Exists (assemblyPath)) {
return assemblyPath;
}
foreach (var dir in searchDirectories) {
var path = Path.Combine (dir, assemblyPath);
if (File.Exists (path))
return path;
}
throw new FileNotFoundException ($"Could not load assembly '{assemblyName}'.", assemblyName);
}
public void Dispose ()
{
foreach (var provider in cache.Values) {
provider.Dispose ();
}
cache.Clear ();
}
}
}