var savedHash = string.Empty;
var assemblyLocation = Assembly.GetEntryAssembly().Location;
// Specify a path to the file that stores your executable’s hash.
// Create this file or load the saved hash if the file already exists:
var hashPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "hash.txt");
if (!File.Exists(hashPath)) {
File.Create(hashPath);
} else {
savedHash = File.ReadAllText(hashPath);
}
// Obtain the hash for your executable.
// Cancel the operation if the application does not have changes:
var hash = string.Concat(SHA1.Create().ComputeHash(File.ReadAllBytes(assemblyLocation))
.Select(x => x.ToString("x2")));
if (hash.Equals(savedHash))
return;
// Obtain the path to ngen.exe:
var dotNetRuntimePath = RuntimeEnvironment.GetRuntimeDirectory();
var ngenPath = Path.Combine(dotNetRuntimePath, "ngen.exe");
// Create a process that runs ngen.exe:
var process = new Process {
StartInfo = new ProcessStartInfo {
FileName = ngenPath,
// Pass the path to your executable:
Arguments = $"install \"{assemblyLocation}\" /nologo",
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
// Run the process as administrator:
UseShellExecute = true,
Verb = "runas"
}
};
// Run the process and save the executable’s hash:
try {
process.Start();
process.WaitForExit();
File.WriteAllText(hashPath, hash);
}
catch {
// Failed to start.
// For example, a user cancelled the UAC prompt.
}
Yorumlar
Yorum Gönder