2011-05-02 130 views
1

我有一個Windows服務,並試圖使用pinvoke來映射它。該代碼在控制檯應用程序中正常工作,但在Windows服務中不起作用。根據這樣的:我需要訪問網絡路徑

"net use" command in a Windows Service

我應該放棄的淨使用方法,而是給予相應的權限,讓自己的服務可以訪問的UNC路徑(\服務器\共享\文件路徑)。我如何設置這些特權?我認爲這是基本的Windows權限,應該設置在某個地方。任何幫助表示讚賞。

[DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] 
internal static extern System.UInt32 NetUseAdd(string UncServerName, int Level, ref USE_INFO_2 Buf, out uint ParmError); 

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] 
internal struct USE_INFO_2 
{ 
    internal LPWSTR ui2_local; 
    internal LPWSTR ui2_remote; 
    internal LPWSTR ui2_password; 
    internal DWORD ui2_status; 
    internal DWORD ui2_asg_type; 
    internal DWORD ui2_refcount; 
    internal DWORD ui2_usecount; 
    internal LPWSTR ui2_username; 
    internal LPWSTR ui2_domainname; 
} 

和...

 static void Main() 
     { 
      USE_INFO_2 useInfo = new USE_INFO_2(); 
      useInfo.ui2_remote = @"\\xx.xx.xx.xx\E$"; // "\\xx.xx.xx.xx\E$" 
      useInfo.ui2_password = "********"; 
      useInfo.ui2_asg_type = 0; //disk drive 
      useInfo.ui2_usecount = 1; 
      useInfo.ui2_username = "Admin"; 
      useInfo.ui2_domainname = "rendering"; 
      uint paramErrorIndex; 
      uint returnCode = NetUseAdd(String.Empty, 2, ref useInfo, out paramErrorIndex); 
      if (returnCode != 0) 
      { 
       throw new Win32Exception((int)returnCode); 
      } 
... 
+6

將您的管理員密碼發佈到世界上的工作很好。對於未來的問題,您應該爲了您自己的安全掩蓋任何可識別的信息。互聯網永遠不會忘記。 :) – 2011-05-02 20:38:37

+0

我現在去睡覺了!謝謝:-)僅供參考,所有敏感信息僅在公司內部網上。 – 2011-05-02 20:51:42

回答

1

你可以啓動你的Windows服務作爲有權限訪問該路徑的網域/ Windows用戶。