gpt4 book ai didi

c# - 从用 C# 编写的 Windows 服务访问映射的文件夹

转载 作者:太空狗 更新时间:2023-10-30 01:24:16 24 4
gpt4 key购买 nike

我有一个 Windows 服务,它轮询特定文件夹以创建新文件。当文件夹位于本地驱动器之一(例如 C: 或 D:该服务无法在映射的驱动器上找到文件夹。

这是在轮询之前检查文件夹是否存在的代码:

System.Security.Principal.WindowsIdentity userIdentity =
System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal =
new System.Security.Principal.WindowsPrincipal(userIdentity);

MappedDriveResolver mdr = new MappedDriveResolver();
if (mdr.isNetworkDrive(folderPath))
{
LoggingAppWrapper.LogDeveloperMessage(folderPath + " is on a Mapped drive", 1, TraceEventType.Information, string.Empty);

}

MappedDriveResolver 是我在这里找到的一个类 How do I determine a mapped drive's actual path?

该链接中的代码在一个简单的控制台应用程序中运行良好,但当它是 Windows 服务的一部分时会失败。关于必须执行哪些操作才能使代码适用于 Windows 服务,有什么建议吗?

问候。

最佳答案

我建议您将服务配置为对不在运行该服务的服务器上的文件夹使用 UNC 路径。

映射驱动器是用户的一项可用性功能,因此它们特定于该用户的配置文件/环境。意思是,当您登录时,您可能有一个驱动器 X: 映射到\\server1\share1,但当我登录时,我的驱动器 X: 可能映射到\\server2\share2。实际的映射过程要么通过“登录时重新连接”保存为您的配置文件的一部分,要么由登录脚本处理。

您需要检查该服务在哪个帐户下运行,并确保该用户环境存在映射驱动器(这可能会有所帮助 How to map a network drive to be used by a service)。

编辑:

您的控制台应用程序工作而服务不工作的原因是它们运行的​​环境之间存在差异。

为了说明这一点,使用这个控制台应用程序,对其进行编译,然后将其作为计划任务运行。将“路径”变量设置为您的用户可以访问的映射驱动器。

    static void Main(string[] args) {
MappedDriveResolver mdr = new MappedDriveResolver();
string logfile;
string path = @"I:\";
string[] files;

// Write out "log" file to where this is running from
logfile = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
logfile = Path.Combine(logfile, "log.txt");

using (StreamWriter sw = new StreamWriter(logfile, true)) {

try {
sw.WriteLine("Checking path " + path);
if (mdr.isNetworkDrive(path)) {
sw.WriteLine("Network Drive: Yes");
} else {
sw.WriteLine("Network Drive: No");
}
} catch (Exception ex) {
sw.WriteLine("Exception: " + ex.Message);
}

try {
sw.WriteLine("Resolve path " + path);
string newpath = mdr.ResolveToUNC(path);
sw.WriteLine("Resolved path " + newpath);
} catch (Exception ex) {
sw.WriteLine("Exception: " + ex.Message);
}

try {
sw.WriteLine("Get file list from " + path);
files = Directory.GetFiles(path);
if (files == null || files.Length == 0) {
sw.WriteLine("No files found");
} else {
sw.WriteLine(string.Format("Found {0} files.", files.Length));
}
} catch (Exception ex) {
sw.WriteLine("Exception: " + ex.Message);
}

sw.Flush();
sw.Close();
}
}

注意:这是与 Windows 7 任务计划程序一起使用

测试 1:只需双击运行该应用即可。
结果:成功

测试 2:使用“仅在用户登录时运行”将计划任务配置为以您的用户帐户运行
结果:成功

测试 3:使用“无论用户是否登录都运行”将计划任务配置为以您的用户帐户运行
结果:异常

测试 4:配置计划任务以“本地服务”帐户运行。
结果:异常

测试 1 和 2 之所以有效,是因为它们使用的是当前登录的用户环境,包括作为其中一部分的映射驱动器。

测试 3 和 4 失败,因为它们有自己的用户环境,没有配置任何映射驱动器。目前我还没有意识到它们之间的区别,但是“交互式”和“非交互式”环境在某些重要方面是不同的。

关于c# - 从用 C# 编写的 Windows 服务访问映射的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9925579/

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