2011-11-17 9 views
10

Windows 파일 공유 서버 (공유되는 폴더)에 파일을 배포하기 위해 .net C# 콘솔 프로그램을 구축 중입니다. 경로는 :: 실행에 \\192.168.0.76\htdocs\public파일 공유, 사용자 인증을 통해 네트워크를 통해 파일 복사

나는 오류 얻고있다 : 나는 나 자신을 인증 할 필요가 있다고 생각

[09:35:29]: [Step 1/3] Unhandled Exception: System.UnauthorizedAccessException: Access to the path '\\192.168.0.76\htdocs\public' is denied. 
[09:35:29]: [Step 1/3] at DeployFileShare.Program.CopyDir(String source, String dest, String[] exclude, Boolean overwrite) 
[09:35:29]: [Step 1/3] at DeployFileShare.Program.Deploy(String num, String source) 
[09:35:29]: [Step 1/3] at DeployFileShare.Program.Main(String[] args) 
[09:35:29]: [Step 1/3] Process exited with code -532459699 

합니다. 나는이 건너했습니다 나는 또한 시도했다

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); 
WindowsIdentity idnt = new WindowsIdentity(username, password); 
WindowsImpersonationContext context = idnt.Impersonate(); 

:

AppDomain.CreateDomain("192.168.0.76").SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); 
WindowsIdentity idnt = new WindowsIdentity("user", "pass"); 
WindowsImpersonationContext context = idnt.Impersonate(); 

내가 그것을 사용하는 방법을 잘 모르겠습니다. 나는 응용 프로그램을 실행할 때 내가 얻을 : 여기

C:\Users\Administrator>DeployFileShare 1 R:\BuildOutput\_PublishedWebsites\Web 2 
1 
Deploy Started Web, version 21 
-- Deploy Prepared 
-- Deploying to 1 

Unhandled Exception: System.Security.SecurityException: There are currently no l 
ogon servers available to service the logon request. 

    at System.Security.Principal.WindowsIdentity.KerbS4ULogon(String upn) 
    at System.Security.Principal.WindowsIdentity..ctor(String sUserPrincipalName, 
String type) 
    at DeployFileShare.Program.Authenticate(String server) 
    at DeployFileShare.Program.Deploy(String num, String source) 
    at DeployFileShare.Program.Main(String[] args) 
The Zone of the assembly that failed was: 
MyComputer 

기본적인 코드 :

static void Main() 
{ 
Copy(); 
} 
static void Copy() 
{ 
AppDomain.CreateDomain(GetServerInfo(server, "server")).SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); 
      WindowsIdentity idnt = new WindowsIdentity(GetServerInfo(server, "user"), GetServerInfo(server, "pass")); 
      WindowsImpersonationContext context = idnt.Impersonate(); 
string source = "C:\\someDir"; 
string dest = "\\192.168.0.76\shareFolder" 
string[] sourceFiles = Directory.GetFiles(source, "*", SearchOption.AllDirectories); 
      foreach (string file in sourceFiles) 
      { 
       string local = file.Replace(source, ""); 
       if (exclude.Contains(local)) 
        continue; 
       if (!Directory.Exists(Path.GetDirectoryName(dest + "\\" + local))) 
        Directory.CreateDirectory(Path.GetDirectoryName(dest + "\\" + local)); 
       File.Copy(file, dest + "\\" + local, overwrite); 
       Console.WriteLine("-- -- [copied] {0} -> {1}", file, dest + "\\" + local); 
      } 
} 

루프 작품, 내 로컬 시스템을 테스트 한의 코드 복사 시스템.

WindowsIdentity 및 WindowsIdentity를 사용하여이 기능을 작동시키는 방법을 아는 분이라면 누구나 저에게 알려주십시오. 나는 주변을 둘러 보았고 윈도우의 문서는별로 도움이되지 않는다.

기본적으로 시스템에 로그인하여 공유되는 원격 디렉토리에 복사 할 수 있습니까?

+1

Powershell을 사용하는 것이 좋습니다. 그런 다음 복사를하기 전에 * \\ 192.168.9.76 \/USER : SomeUser 을 사용할 수 있습니다 (Robocopy.exe ...를 사용합니다). –

+0

@JamesJohnson 우리는 VMware에서 작업하기 때문에 IP를 사용하고 있습니다. VMware에서이 프로그램을 다른 도메인에서 실행하도록 컴퓨터를 설정하십시오. 따라서 컴퓨터 이름이 작동하지 않습니다. –

+0

더 보편적 인 방법이 있다고 생각합니다. http://stackoverflow.com/questions/295538/how-to-provide-user-name-and-password-when-connecting-to-a-network-share/39540451# 39540451 –

답변

5

VB이지만 쉽게 C#으로 번역되었습니다. 당신의 사본 전에이 작업을 수행 :

Private Sub Open_Remote_Connection(ByVal strComputer As String, ByVal strUserName As String, ByVal strPassword As String) 
    Dim ProcessStartInfo As New System.Diagnostics.ProcessStartInfo 
    ProcessStartInfo.FileName = "net" 
    ProcessStartInfo.Arguments = "use \\" & strComputer & "\c$ /USER:" & strUsername & " " & strPassword 
    ProcessStartInfo.WindowStyle = ProcessWindowStyle.Hidden 
    System.Diagnostics.Process.Start(ProcessStartInfo) 
    System.Threading.Thread.Sleep(2000) 
End Sub 
5

당신이 파일을 이동하기 위해 원격 컴퓨터에 인증하려는 경우, 당신은 당신의 사용자를 가장하고 WindowsIdentity에 LogonUser 기능을 사용할 수 있습니다.

/// <summary> 
/// Exécute une fonction en empruntant les credentials 
/// </summary> 
private T ApplyCredentials<T>(Func<T> func) 
{ 
    IntPtr token; 

    if (!LogonUser(
     _credentials.UserName, 
     _credentials.Domain, 
     _credentials.Password, 
     LOGON32_LOGON_INTERACTIVE, 
     LOGON32_PROVIDER_DEFAULT, 
     out token)) 
    { 
     Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); 
    } 

    try 
    { 
     // On doit être impersonifié seulement le temps d'ouvrir le handle. 
     using (var identity = new WindowsIdentity(token)) 
     using (var context = identity.Impersonate()) 
     { 
      return func(); 
     } 
    } 
    finally 
    { 
     CloseHandle(token); 
    } 
} 

// ... 

if (_credentials != null) 
{ 
    return this.ApplyCredentials(() => File.Open(path, mode, access, share)); 
} 

return File.Open(path, mode, access, share);