gpt4 book ai didi

c# - 使 Windows 服务像从特定用户运行一样运行

转载 作者:行者123 更新时间:2023-11-30 20:56:50 25 4
gpt4 key购买 nike

我想创建一个 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());
}
}

该代码基本上是挂载一个卷写入它并卸载它。如果我运行该程序,这就是我所看到的:

enter image description here

  1. 当我打开程序 trueCrypt.exe 时,我可以看到该卷实际上已安装。
  2. 我可以看到程序实际上写入了文件 someFile.txt
  3. 路径 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com