问题
I want to create a windows service to mount and dismount a True Crypt volume.
(this question is not about true crypt so if you do not know what that program that is ok. True Crypt is just a program that enables you to encrypt data. When you decrypt it then trueCrypt will create a virtual drive where you can see the contents unencrypted).
Here is the code I use in my console application:
static void Main(string[] args)
{
Test();
}
static void Test()
{
try
{
// location where true crypt is installed
const string trueCryptExeLocation = @"C:\Program Files\TrueCrypt\TrueCrypt.exe";
// command line arguments to mount a volume located at 'C:\TC Volumes\vol1.tc' where
// it's password is 'demo' and it will be mounted on drive letter y
const string mountVolumeCmd = @"/v ""C:\TC Volumes\vol1.tc"" /ly /q /p demo /f /a";
// mount the volume on drive letter y
Process.Start(trueCryptExeLocation, mountVolumeCmd).WaitForExit();
// write to the volume!
System.IO.File.WriteAllText("y:\\someFile.txt", "it works");
// wait 30 seconds before dismounting
Thread.Sleep(3000);
// dismount the volume
Process.Start(@"C:\Program Files\TrueCrypt\TrueCrypt.exe", @"/ly /q /d /f");
}
catch (Exception ex)
{
// if there is an error write it to disk
System.IO.File.WriteAllText(@"A:\Dropbox\Eduardo\WindowsNodeService\WindowsNodeService\bin\Debug\startup.txt", ex.ToString());
}
}
That code basically mounts a volume writes to it and dismounts it. IF I run that program this is what I see:

- When I open the program trueCrypt.exe I can see that the volume is actually mounted.
- I can see that the program actually wrote to the file someFile.txt
- The path
Y:\
exist. In other words I can open My Computer and see drive Y.
Now my question is why if I run the same code on a windows service it runs differently but it runns ok with no errors.
In other words having the following windows service:
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
Test(); // same method as console application
}
protected override void OnStop()
{
}
// etc... Test method implementation
Running that code runs fine. It writes to the file someFile.txt! which is great. The problem is that if I open trueCrypt I do not see the volume mounted in there. Also if I go to My Computer I do not see the drive Y. How can I make my windows service behave like the console application?
回答1:
If you're using .Net 4.5, you can use this Process.Start call:
Code from MSDN:
Process.Start(path + "HelloWorld.exe", args, uname, password, domain);
回答2:
Austin's answer should work for the specific case. However, if you just want to know how to do this at installation time, then you want to use the ServiceProcess.ServiceAccount property. An example with more details can be found here
You might want to try the LocalSystem
ServiceAccount type.
来源:https://stackoverflow.com/questions/17304400/make-windows-service-run-as-if-it-was-run-from-a-specific-user