2012-03-26 79 views
2

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

回答

3

我建议UNC是一个更好的主意。

如果映射的驱动器在登录时被映射,该怎么办?即使登录,服务也可能在没有用户的情况下运行,因此可能永远不会创建映射。

3

我们也经历过这种情况,虽然我不能告诉你为什么我们的决议起作用了,但我可以告诉你什么是成功的。

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

根据我们所看到的行为,这就是我会在我们的情况中发生GUESS的情况,以及您的情况。

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

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

请注意,您也可以直接引用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; 
     } 

    } 

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

+0

这不适用于多个同时连接尝试。 – 2013-10-17 13:46:28

0

我挣扎了很多(〜3天)来解决同样的问题。似乎它与NTFS和文件级权限更相关。如果您使用共享位置而不是驱动器,则会更好。

相关问题