我想创建一个 Windows 服务来安装和卸载 True Crypt体积。
(这个问题与 true crypt 无关,所以如果您不知道该程序是什么也没关系。True Crypt 只是一个使您能够加密数据的程序。当您解密它时,trueCrypt 将创建一个虚拟驱动器,您可以在其中创建一个虚拟驱动器。可以看到未加密的内容)。
这是我在控制台应用程序中使用的代码:
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());
}
}
该代码基本上安装了一个卷,写入它并卸载它。如果我运行该程序,这就是我看到的:
- 当我打开程序 trueCrypt.exe 时,我可以看到该卷实际上已安装。
- 我可以看到程序实际上写入了文件 someFile.txt
- 路径
Y:\
存在。换句话说,我可以打开“我的电脑”并看到驱动器 Y。
现在我的问题是,为什么如果我在 Windows 服务上运行相同的代码,它会以不同的方式运行,但运行正常,没有错误。
换句话说,拥有以下 Windows 服务:
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
运行该代码运行良好。它写入文件 someFile.txt!这太棒了。问题是,如果我打开 trueCrypt,我看不到安装在其中的卷。另外,如果我转到“我的电脑”,我看不到驱动器 Y。如何使我的 Windows 服务表现得像控制台应用程序?
最佳答案
如果您使用的是.Net 4.5,则可以使用this Process.Start call :
来自 MSDN 的代码:
Process.Start(path + "HelloWorld.exe", args, uname, password, domain);
关于c# - 使 Windows 服务像从特定用户运行一样运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17304400/