systeminfo.cs
来自「SharpDevelop2.0.0 c#开发免费工具」· CS 代码 · 共 1,003 行 · 第 1/2 页
CS
1,003 行
public static Type GetTypeFromString(Type relativeType, string typeName, bool throwOnError, bool ignoreCase)
{
return GetTypeFromString(relativeType.Assembly, typeName, throwOnError, ignoreCase);
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the
/// assembly that is directly calling this method. If the type is not found
/// in the assembly then all the loaded assemblies will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(string typeName, bool throwOnError, bool ignoreCase)
{
return GetTypeFromString(Assembly.GetCallingAssembly(), typeName, throwOnError, ignoreCase);
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="relativeAssembly">An assembly to load the type from.</param>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the specified
/// assembly. If the type is not found in the assembly then all the loaded assemblies
/// will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, bool throwOnError, bool ignoreCase)
{
// Check if the type name specifies the assembly name
if(typeName.IndexOf(',') == -1)
{
//LogLog.Debug("SystemInfo: Loading type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
#if NETCF
return relativeAssembly.GetType(typeName, throwOnError);
#else
// Attempt to lookup the type from the relativeAssembly
Type type = relativeAssembly.GetType(typeName, false, ignoreCase);
if (type != null)
{
// Found type in relative assembly
//LogLog.Debug("SystemInfo: Loaded type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
return type;
}
Assembly[] loadedAssemblies = null;
try
{
loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
}
catch(System.Security.SecurityException)
{
// Insufficient permissions to get the list of loaded assemblies
}
if (loadedAssemblies != null)
{
// Search the loaded assemblies for the type
foreach (Assembly assembly in loadedAssemblies)
{
type = assembly.GetType(typeName, false, ignoreCase);
if (type != null)
{
// Found type in loaded assembly
LogLog.Debug("SystemInfo: Loaded type ["+typeName+"] from assembly ["+assembly.FullName+"] by searching loaded assemblies.");
return type;
}
}
}
// Didn't find the type
if (throwOnError)
{
throw new TypeLoadException("Could not load type ["+typeName+"]. Tried assembly ["+relativeAssembly.FullName+"] and all loaded assemblies");
}
return null;
#endif
}
else
{
// Includes explicit assembly name
//LogLog.Debug("SystemInfo: Loading type ["+typeName+"] from global Type");
#if NETCF
return Type.GetType(typeName, throwOnError);
#else
return Type.GetType(typeName, throwOnError, ignoreCase);
#endif
}
}
/// <summary>
/// Generate a new guid
/// </summary>
/// <returns>A new Guid</returns>
/// <remarks>
/// <para>
/// Generate a new guid
/// </para>
/// </remarks>
public static Guid NewGuid()
{
#if NETCF
return PocketGuid.NewGuid();
#else
return Guid.NewGuid();
#endif
}
/// <summary>
/// Create an <see cref="ArgumentOutOfRangeException"/>
/// </summary>
/// <param name="parameterName">The name of the parameter that caused the exception</param>
/// <param name="actualValue">The value of the argument that causes this exception</param>
/// <param name="message">The message that describes the error</param>
/// <returns>the ArgumentOutOfRangeException object</returns>
/// <remarks>
/// <para>
/// Create a new instance of the <see cref="ArgumentOutOfRangeException"/> class
/// with a specified error message, the parameter name, and the value
/// of the argument.
/// </para>
/// <para>
/// The Compact Framework does not support the 3 parameter constructor for the
/// <see cref="ArgumentOutOfRangeException"/> type. This method provides an
/// implementation that works for all platforms.
/// </para>
/// </remarks>
public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message)
{
#if NETCF
return new ArgumentOutOfRangeException(message + " param: " + parameterName + " value: " + actualValue);
#else
return new ArgumentOutOfRangeException(parameterName, actualValue, message);
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int32"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out int val)
{
#if NETCF
val = 0;
try
{
val = int.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt32(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int64"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out long val)
{
#if NETCF
val = 0;
try
{
val = long.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt64(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Convert a path into a fully qualified local file path.
/// </summary>
/// <param name="path">The path to convert.</param>
/// <returns>The fully qualified path.</returns>
/// <remarks>
/// <para>
/// Converts the path specified to a fully
/// qualified path. If the path is relative it is
/// taken as relative from the application base
/// directory.
/// </para>
/// <para>
/// The path specified must be a local file path, a URI is not supported.
/// </para>
/// </remarks>
public static string ConvertToFullPath(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
string baseDirectory = "";
try
{
string applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
if (applicationBaseDirectory != null)
{
// applicationBaseDirectory may be a URI not a local file path
Uri applicationBaseDirectoryUri = new Uri(applicationBaseDirectory);
if (applicationBaseDirectoryUri.IsFile)
{
baseDirectory = applicationBaseDirectoryUri.LocalPath;
}
}
}
catch
{
// ignore uri exceptions
}
if (baseDirectory != null && baseDirectory.Length > 0)
{
// Note that Path.Combine will return the second path if it is rooted
return Path.GetFullPath(Path.Combine(baseDirectory, path));
}
return Path.GetFullPath(path);
}
#endregion Public Static Methods
#region Private Static Methods
#if NETCF
private static string NativeEntryAssemblyLocation
{
get
{
StringBuilder moduleName = null;
IntPtr moduleHandle = GetModuleHandle(IntPtr.Zero);
if (moduleHandle != IntPtr.Zero)
{
moduleName = new StringBuilder(255);
if (GetModuleFileName(moduleHandle, moduleName, moduleName.Capacity) == 0)
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
}
else
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
return moduleName.ToString();
}
}
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern IntPtr GetModuleHandle(IntPtr ModuleName);
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern Int32 GetModuleFileName(
IntPtr hModule,
StringBuilder ModuleName,
Int32 cch);
#endif
#endregion Private Static Methods
#region Public Static Fields
/// <summary>
/// Gets an empty array of types.
/// </summary>
/// <remarks>
/// <para>
/// The <c>Type.EmptyTypes</c> field is not available on
/// the .NET Compact Framework 1.0.
/// </para>
/// </remarks>
public static readonly Type[] EmptyTypes = new Type[0];
#endregion Public Static Fields
#region Private Static Fields
/// <summary>
/// Cache the host name for the current machine
/// </summary>
private static string s_hostName;
/// <summary>
/// Cache the application friendly name
/// </summary>
private static string s_appFriendlyName;
#endregion
#region Compact Framework Helper Classes
#if NETCF
/// <summary>
/// Generate GUIDs on the .NET Compact Framework.
/// </summary>
public class PocketGuid
{
// guid variant types
private enum GuidVariant
{
ReservedNCS = 0x00,
Standard = 0x02,
ReservedMicrosoft = 0x06,
ReservedFuture = 0x07
}
// guid version types
private enum GuidVersion
{
TimeBased = 0x01,
Reserved = 0x02,
NameBased = 0x03,
Random = 0x04
}
// constants that are used in the class
private class Const
{
// number of bytes in guid
public const int ByteArraySize = 16;
// multiplex variant info
public const int VariantByte = 8;
public const int VariantByteMask = 0x3f;
public const int VariantByteShift = 6;
// multiplex version info
public const int VersionByte = 7;
public const int VersionByteMask = 0x0f;
public const int VersionByteShift = 4;
}
// imports for the crypto api functions
private class WinApi
{
public const uint PROV_RSA_FULL = 1;
public const uint CRYPT_VERIFYCONTEXT = 0xf0000000;
[DllImport("coredll.dll")]
public static extern bool CryptAcquireContext(
ref IntPtr phProv, string pszContainer, string pszProvider,
uint dwProvType, uint dwFlags);
[DllImport("coredll.dll")]
public static extern bool CryptReleaseContext(
IntPtr hProv, uint dwFlags);
[DllImport("coredll.dll")]
public static extern bool CryptGenRandom(
IntPtr hProv, int dwLen, byte[] pbBuffer);
}
// all static methods
private PocketGuid()
{
}
/// <summary>
/// Return a new System.Guid object.
/// </summary>
public static Guid NewGuid()
{
IntPtr hCryptProv = IntPtr.Zero;
Guid guid = Guid.Empty;
try
{
// holds random bits for guid
byte[] bits = new byte[Const.ByteArraySize];
// get crypto provider handle
if (!WinApi.CryptAcquireContext(ref hCryptProv, null, null,
WinApi.PROV_RSA_FULL, WinApi.CRYPT_VERIFYCONTEXT))
{
throw new SystemException(
"Failed to acquire cryptography handle.");
}
// generate a 128 bit (16 byte) cryptographically random number
if (!WinApi.CryptGenRandom(hCryptProv, bits.Length, bits))
{
throw new SystemException(
"Failed to generate cryptography random bytes.");
}
// set the variant
bits[Const.VariantByte] &= Const.VariantByteMask;
bits[Const.VariantByte] |=
((int)GuidVariant.Standard << Const.VariantByteShift);
// set the version
bits[Const.VersionByte] &= Const.VersionByteMask;
bits[Const.VersionByte] |=
((int)GuidVersion.Random << Const.VersionByteShift);
// create the new System.Guid object
guid = new Guid(bits);
}
finally
{
// release the crypto provider handle
if (hCryptProv != IntPtr.Zero)
WinApi.CryptReleaseContext(hCryptProv, 0);
}
return guid;
}
}
#endif
#endregion Compact Framework Helper Classes
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?