找不到路径的一部分:使用 Windows 服务在映射驱动器上复制文件时

Ris*_*esh 4 .net c#

我有一个 Windows 服务,它会更新网络上映射为驱动器“Z:\”的一些文件。当我以管理员身份从 VS 运行代码时,我能够复制映射驱动器上的文件,但是当它从在管理员帐户下运行的服务运行时,同样的事情会失败。映射驱动器是从运行服务的同一帐户创建的。有点令人困惑,为什么它在从 VS 运行而不是从服务运行时工作。使用 UNC 比使用网络驱动器更好。下面的论坛http://support.microsoft.com/default.aspx?scid=kb;en-us;827421#appliesto有一个解决方法, 但它使用了 UNC 未映射的驱动器。

Dav*_*vid 5

我们也经历过这种情况,虽然我不能告诉你为什么我们的决议有效,但我可以告诉你什么有效。

在代码中映射驱动器。不要仅仅因为您使用相同的帐户就依赖被映射的驱动器。

根据我们看到的行为,这就是我猜测在我们的情况下正在发生的情况以及在您的情况下正在发生的情况。

我们遇到问题的服务使用了在登录脚本中映射的驱动器。如果我们让机器以服务使用的同一用户身份登录,它可以工作,但如果不是,它将无法工作。基于此,我推测驱动器根本没有映射,因为该服务并没有真正“登录”。

在代码中映射驱动器修复了它。

作为旁注,您也可以直接引用 UNC 路径,但我们也有权限问题。映射驱动器,传入用户名和密码对我们来说效果更好。

我们这样做的代码:

public static class NetworkDrives
    {
        public static bool  MapDrive(string DriveLetter, string Path, string Username, string Password)
        {

            bool ReturnValue = false;

            if(System.IO.Directory.Exists(DriveLetter + ":\\"))
            {
                DisconnectDrive(DriveLetter);
            }
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;

            p.StartInfo.FileName = "net.exe";
            p.StartInfo.Arguments = " use " + DriveLetter + ": " + '"' + Path + '"' + " " + Password + " /user:" + Username;
            p.Start();
            p.WaitForExit();

            string ErrorMessage = p.StandardError.ReadToEnd();
            string OuputMessage = p.StandardOutput.ReadToEnd();
            if (ErrorMessage.Length > 0)
            {
                throw new Exception("Error:" + ErrorMessage);
            }
            else
            {
                ReturnValue = true;
            }
            return ReturnValue;
        }
        public static bool DisconnectDrive(string DriveLetter)
        {
            bool ReturnValue = false;
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;

            p.StartInfo.FileName = "net.exe";
            p.StartInfo.Arguments = " use " + DriveLetter + ": /DELETE";
            p.Start();
            p.WaitForExit();

            string ErrorMessage = p.StandardError.ReadToEnd();
            string OuputMessage = p.StandardOutput.ReadToEnd();
            if (ErrorMessage.Length > 0)
            {
                throw new Exception("Error:" + ErrorMessage);
            }
            else
            {
                ReturnValue = true;
            }
            return ReturnValue;
        }

    }
Run Code Online (Sandbox Code Playgroud)

使用上面的类,你可以随意映射和断开驱动器。如果这是一项服务,我建议您在需要之前映射驱动器,并在需要后立即断开驱动器。