I was wondering if its possible to call an event or method the first time a program starts up, and obviously on the first time. Is this possible to do in C#? If so could someone show 开发者_如何学运维some examples of how this is accomplished
You can write a file to disk or a value to the registry when the program is run the first time.
You check the existence of whatever you set - if it doesn't exist, you run your method, if it does, you don't.
You could use the MoveFileEx native method by specifying the DelayUntilReboot
flag on some lock file:
class Program
{
[Flags]
enum MoveFileFlags
{
None = 0,
ReplaceExisting = 1,
CopyAllowed = 2,
DelayUntilReboot = 4,
WriteThrough = 8,
CreateHardlink = 16,
FailIfNotTrackable = 32,
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool MoveFileEx(
string lpExistingFileName,
string lpNewFileName,
MoveFileFlags dwFlags
);
static void Main()
{
string lockFile = "foo.dat";
if (!File.Exists(lockFile))
{
// that's a first run after the reboot => create the file
File.WriteAllText(lockFile, "");
// Mark the file for deletion after reboot
MoveFileEx(lockFile, null, MoveFileFlags.DelayUntilReboot);
Console.WriteLine("it's a first run");
}
else
{
// that's a consecutive run
Console.WriteLine("it's a consecutive run");
}
}
}
精彩评论