/*
Copyright (C) 2014-2019 de4dot@gmail.com
This file is part of dnSpy
dnSpy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
dnSpy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with dnSpy. If not, see .
*/
using System;
using System.ComponentModel;
using System.Reflection;
namespace dnSpy.Contracts.Images {
///
/// Image reference
///
[TypeConverter(typeof(ImageReferenceConverter))]
public readonly struct ImageReference {
///
/// Gets an which isn't referencing any image
///
public static readonly ImageReference None = default;
///
/// true if it's the default instance
///
public bool IsDefault => Assembly is null && Name is null;
///
/// Assembly of image or null if is a URI
///
public Assembly? Assembly { get; }
///
/// Name of image
///
public string Name { get; }
///
/// Constructor
///
/// Assembly of image or null if is a pack: URI
/// Name of image
public ImageReference(Assembly? assembly, string name) {
Assembly = assembly;
Name = name ?? throw new ArgumentNullException(nameof(name));
}
///
/// Parses a string and tries to create an
///
/// String to parse
/// Result
///
public static bool TryParse(string? value, out ImageReference result) {
result = default;
if (value is null)
return false;
if (value == string.Empty)
return true;
if (value.StartsWith("/", StringComparison.OrdinalIgnoreCase) ||
value.StartsWith("pack:", StringComparison.OrdinalIgnoreCase) ||
value.StartsWith("file:", StringComparison.OrdinalIgnoreCase)) {
result = new ImageReference(null, value);
return true;
}
int index = value.IndexOf(',');
if (index < 0) {
result = new ImageReference(null, value);
return true;
}
var asmName = value.Substring(0, index).Trim();
var name = value.Substring(index + 1).Trim();
Assembly asm;
try {
asm = Assembly.Load(asmName);
}
catch {
return false;
}
result = new ImageReference(asm, name);
return true;
}
///
/// Converts this instance to a string that can be passed to
///
///
public override string ToString() {
if (IsDefault)
return string.Empty;
if (Assembly is null)
return Name;
return Assembly.GetName().Name + "," + Name;
}
}
}