2013-04-05 2 views
3

디렉토리가 로컬 네트워크가 아닌지 확인하려고합니다. stackoverflow 및 MSDN에 대한 연구가 끝나면, 나는 impersonate 메서드를 사용하여 코드를 개발합니다. 여기C# Directory.exist는 로컬 네트워크에서 항상 false를 반환합니다.

public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid 
    { 
     private SafeTokenHandle() 
      : base(true) 
     { 
     } 

     [DllImport("kernel32.dll")] 
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] 
     [SuppressUnmanagedCodeSecurity] 
     [return: MarshalAs(UnmanagedType.Bool)] 
     private static extern bool CloseHandle(IntPtr handle); 

     protected override bool ReleaseHandle() 
     { 
      return CloseHandle(handle); 
     } 
    } 

class Environment 
    { 
     [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] 
     public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, 
      int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken); 

     [DllImport("kernel32.dll", CharSet = CharSet.Auto)] 
     public extern static bool CloseHandle(IntPtr handle); 
     const int LOGON32_PROVIDER_DEFAULT = 0; 
     const int LOGON32_LOGON_INTERACTIVE = 2; 

     private void m_SendAlertes() 
     { 
       SafeTokenHandle safeTokenHandle; 
       string v_pathToDir = "\\192.168.1.199\Clients SiteInternet"; 

       if (!LogonUser("RKalculateur", "SERVEUR2", 
           "riskedge", LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle)) 
       { 
        int ret = Marshal.GetLastWin32Error(); 
        throw new System.ComponentModel.Win32Exception(ret); 
       } 
       using (safeTokenHandle) 
       { 
        using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle())) 
        { 
         using (WindowsImpersonationContext impersonatedUser = newId.Impersonate()) 
         { 
          if (Directory.Exists(@v_pathToDir)) 
          { 
           // Proceed code here 
          } 
         } 
        } 
       } 
     } 
    } 

당신이이 디렉토리에 권리의 사진을 가지고 : 문제는 아주 잘 작동하지 않습니다는 Directory.exists() 방법은 항상 (이 거의 MSDN의 것과 동일합니다) 당신이 내 코드가 여기에 False을 반환 : enter image description here

+0

wpf, win forms 또는 웹 앱입니까? –

+0

그냥 C에서 정상적인 터미널 프로그램 # –

+0

@ LukeMarlin 나는이 게시물을 이미 읽었지만 실제로 어떻게하는지 이해하지 못한다 : s ... 그리고 나는 IIS가 무엇인지 모른다. –

답변

4

아마도 사용자 권한에 연결된 문제 일 수 있습니다.

MSDN에서

: 당신이 디렉토리에 최소 읽기 전용 권한에없는 경우

는 메소드가 false를 돌려줍니다 존재한다.

도메인 계정이 아닌 도메인 계정을 사용하는 경우 Directory.Exists() 메소드를 사용할 때 문제가 발생합니다.

과거에도 비슷한 문제가있었습니다. 네트워크에 실제 공유가 있는지, 도메인이 없는지 확인해야했습니다. 너의 길은 나를 위해 일하지 않았다. 결국, 나는() 메소드 Directory.Exists에 포기하고 나는 그것이 해킹 알고 NET USE 명령 (http://www.cezeo.com/tips-and-tricks/net-use-command/)

bool exists = false; 
string output = ""; 
string error = ""; 

System.Diagnostics.Process process = new System.Diagnostics.Process(); 
process = new System.Diagnostics.Process(); 
      ExecuteShellCommand(process, "NET USE", "\""+ @path + "\" "+ 
       this.password+ " /USER:"+machinename+"\\"+username + " /PERSISTENT:NO", 
       ref output, ref error); 
Console.WriteLine("\r\n\t__________________________"+ 
       "\r\n\tOutput:" + output.Trim().Replace("\r", " ") + 
       "\r\n\tError: " + error.Trim().Replace("\r"," ")); 

      if (output.Length>0 && error.Length==0) 
      { 
       exists = true; 
      } 

      process = new System.Diagnostics.Process(); 
      ExecuteShellCommand(process, "NET USE", " /DELETE " + @path, 
       ref output, ref error); 

....

public void ExecuteShellCommand(System.Diagnostics.Process process, string fileToExecute, 
     string command, ref string output, ref string error) 
    { 
     try 
     { 
      string CMD = string.Format(System.Globalization.CultureInfo.InvariantCulture, @"{0}\cmd.exe", new object[] { Environment.SystemDirectory }); 
      string args = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/C {0}", new object[] { fileToExecute }); 
      if (command != null && command.Length > 0) 
      { 
       args += string.Format(System.Globalization.CultureInfo.InvariantCulture, " {0}", new object[] { command, System.Globalization.CultureInfo.InvariantCulture }); 
      } 

      System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(CMD, args); 

      startInfo.CreateNoWindow = true; 
      startInfo.UseShellExecute = false; 
      startInfo.RedirectStandardOutput = true; 
      startInfo.RedirectStandardInput = true; 
      startInfo.RedirectStandardError = true; 

      process.StartInfo = startInfo; 

      process.Start(); 

      // timeout 
process.WaitForExit(10 * 1000); 
output = process.StandardOutput.ReadToEnd(); 
      error = process.StandardError.ReadToEnd(); 
     } 
     catch (Win32Exception e32) 
     { 
      Console.WriteLine("Win32 Exception caught in process: {0}", e32.ToString()); 
     } 
     catch (Exception e 
     { 
      Console.WriteLine("Exception caught in process: {0}", e.ToString()); 
     } 
     finally 
     { 
      // close process and do cleanup 
      process.Close(); 
      process.Dispose(); 
      process = null; 
     } 
    } 

를 사용하여 종료하지만 일 나를 위해 그것은 가능성이있다. (적절한 네트워크 공유를 설정해야 할 수도 있음)