quarta-feira, 12 de novembro de 2008

Acesso a pastas ou arquivos de outra máquina

O código abaixo demonstra como exibir arquivos ou pastas de uma outra máquina que não seja a máquina na qual se encontra a aplicação.

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Diagnostics; 
using System.IO; 
using System.Net; 
using System.Security.Principal; 
using System.Runtime.InteropServices;

namespace Cronos.Testes 
{ 
    class Program 
    {

        [DllImport("advapi32.dll", SetLastError = true)] 
        private static extern bool LogonUser(string lpszUsername 
                                            , string lpszDomain 
                                            , string lpszPassword 
                                            , int dwLogonType 
                                            , int dwLogonProvider 
                                            , ref IntPtr phToken);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
        private static extern bool CloseHandle(IntPtr handle);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
        public extern static bool DuplicateToken(IntPtr existingTokenHandle 
                                                , int SECURITY_IMPERSONATION_LEVEL 
                                                , ref IntPtr duplicateTokenHandle);


        // logon types 
        const int LOGON32_LOGON_INTERACTIVE = 2; 
        const int LOGON32_LOGON_NETWORK = 3; 
        const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

        // logon providers 
        const int LOGON32_PROVIDER_DEFAULT = 0; 
        const int LOGON32_PROVIDER_WINNT50 = 3; 
        const int LOGON32_PROVIDER_WINNT40 = 2; 
        const int LOGON32_PROVIDER_WINNT35 = 1;

        static void Main(string[] args) 
        { 
            IntPtr token = IntPtr.Zero; 
            IntPtr dupToken = IntPtr.Zero;

            bool isSuccess = LogonUser("[myUser]" 
                                        , @"[myDomain]" 
                                        , @"[myPass]" 
                                        , LOGON32_LOGON_NEW_CREDENTIALS 
                                        , LOGON32_PROVIDER_DEFAULT 
                                        , ref token);

            WindowsIdentity newIdentity = new WindowsIdentity(token); 
            WindowsImpersonationContext impersonatedUser = newIdentity.Impersonate();

            DirectoryInfo dirInfo = new DirectoryInfo(@"\\[caminho ou ip da outra máquina]\C$\"); 
            FileInfo[] files = dirInfo.GetFiles();


            for (int i = 0; i <> 
            { 
                Console.WriteLine(files[i].Name); 
            }

            Console.Read(); 
        } 
    } 
}

Créditos: Luiz Fernando.

Nenhum comentário: