2012-03-26 80 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和文件級權限更相關。如果您使用共享位置而不是驅動器,則會更好。

相關問題