none
Access a network drive (ip/folder) programmatically to create folder, write files and copy files RRS feed

  • Question

  • Hi All,

    We have windows form application using C# , which has to do the below functionality to network drive 

    1,  create new folder,

    2 delete, create new file 

    3 , copy file from shared drive to local folder


    The shared drive is exactly like \\192.XX.XX.X2\Repository\Repo1

    Currently we have users connecting out office network via Vpn

    and some user connect directly to network from office.


    Can you please help me how to programmatically connect inside the application with out any prompt window to copy files and create folders  from local pc to the shared drive path mentioned above.

    Requirement is copy file of size ranging from 1 MB up-to 20MB

    Thanks,

    Have a nice day ahead.


    • Edited by techasuran Thursday, April 2, 2020 5:04 AM
    Thursday, April 2, 2020 5:03 AM

Answers

  • Hi techasuran,

    Thank you for posting here.

    Here's the code about using impersonation in order for your code to execute as a certain user and then move the file in shared folder to local folder.

    private void button1_Click(object sender, EventArgs e)
            {
                string domain = "your domain";
                string userName = "your username";
                string userPassword = "your password";
                ImpersonationHelper.Impersonate(domain, userName, userPassword, delegate
                {
                    string SourcePath = @"path of shared folder";
                    string DestinationPath = "path of local folder";
    
                    foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",SearchOption.AllDirectories))
                        Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
                    //Copy all the files & Replaces any files with the same name
                    foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
                        SearchOption.AllDirectories))
                        File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);
                });
            }
    
        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);
            }
        }
        public class ImpersonationHelper
        {
            [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
            private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
            int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
    
            [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
            private extern static bool CloseHandle(IntPtr handle);
    
            [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
            public static void Impersonate(string domainName, string userName, string userPassword, Action actionToExecute)
            {
                SafeTokenHandle safeTokenHandle;
                try
                {
                    const int LOGON32_PROVIDER_DEFAULT = 0;
                    //This parameter causes LogonUser to create a primary token.
                    const int LOGON32_LOGON_INTERACTIVE = 2;
                    // Call LogonUser to obtain a handle to an access token.
                    bool returnValue = LogonUser(userName, domainName, userPassword,
                        LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                        out safeTokenHandle);
                    if (returnValue == false)
                    {
                        int ret = Marshal.GetLastWin32Error();
                        throw new System.ComponentModel.Win32Exception(ret);
                    }
    
                    using (safeTokenHandle)
                    {
                        // Use the token handle returned by LogonUser.
                        using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                        {
                            using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                            {
                                actionToExecute();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }

    Hope it could be helpful.

    Please let me know if you need further assistance.

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.



    Friday, April 3, 2020 7:51 AM
    Moderator

All replies

  • Hi techasuran,

    Thank you for posting here.

    Here's the code about using impersonation in order for your code to execute as a certain user and then move the file in shared folder to local folder.

    private void button1_Click(object sender, EventArgs e)
            {
                string domain = "your domain";
                string userName = "your username";
                string userPassword = "your password";
                ImpersonationHelper.Impersonate(domain, userName, userPassword, delegate
                {
                    string SourcePath = @"path of shared folder";
                    string DestinationPath = "path of local folder";
    
                    foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",SearchOption.AllDirectories))
                        Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
                    //Copy all the files & Replaces any files with the same name
                    foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
                        SearchOption.AllDirectories))
                        File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);
                });
            }
    
        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);
            }
        }
        public class ImpersonationHelper
        {
            [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
            private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
            int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
    
            [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
            private extern static bool CloseHandle(IntPtr handle);
    
            [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
            public static void Impersonate(string domainName, string userName, string userPassword, Action actionToExecute)
            {
                SafeTokenHandle safeTokenHandle;
                try
                {
                    const int LOGON32_PROVIDER_DEFAULT = 0;
                    //This parameter causes LogonUser to create a primary token.
                    const int LOGON32_LOGON_INTERACTIVE = 2;
                    // Call LogonUser to obtain a handle to an access token.
                    bool returnValue = LogonUser(userName, domainName, userPassword,
                        LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                        out safeTokenHandle);
                    if (returnValue == false)
                    {
                        int ret = Marshal.GetLastWin32Error();
                        throw new System.ComponentModel.Win32Exception(ret);
                    }
    
                    using (safeTokenHandle)
                    {
                        // Use the token handle returned by LogonUser.
                        using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                        {
                            using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                            {
                                actionToExecute();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }

    Hope it could be helpful.

    Please let me know if you need further assistance.

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.



    Friday, April 3, 2020 7:51 AM
    Moderator
  • Hi XingYu,

    I have a situation here.

    There are some contractors who connects to our vpn , but their machine is not added to our domain.

    When the try to access this folder by this users its  not working.

    its the same case if these contractor come to our office and connect to network , but still their machines are not in our domain.

    do the machines also to be in domain to avail this fucntionlity?

    Please let us know your thoughts on this.

    Below is the code I am using, its slightly different from what you pasted above.

    thanks in advance.

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Security.Principal;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace FileOp.Services
    {
        public class Impersonate
        {
            public static string _userName;
            public static string _domain;
            public static string _password;
    
            [DllImport("kernel32.dll")]
            private static extern bool CloseHandle(IntPtr token);
    
            [DllImport("advapi32.dll", SetLastError = true)]
            private static extern bool LogonUser(string username, string domain, string password, int logonType, int logonProvider, ref IntPtr token);
    
    
            /// <summary>
            /// Copies a source file to the destination path using win32.dll and winodws impersonation, 
            /// create the destination directory if it doesnt exists
            /// </summary>
            /// <param name="sourcePath">complete source file path including the filename</param>
            /// <param name="destPath">complete destination file path including the filename</param>
            /// <returns></returns>
            public static bool CopyFile(string sourcePath, string destPath)
            {
                bool copyStatus = true;
                IntPtr token = IntPtr.Zero;
                bool isValid = LogonUser(_userName,
                                        _domain,
                                        _password,
                                        (int)LogonType.Interactive,
                                        (int)LogonProvider.Default,
                                        ref token);
                if (!isValid)
                {
                    copyStatus = false;
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new System.ComponentModel.Win32Exception(errorCode);
                }
    
                using (WindowsImpersonationContext UserContext = WindowsIdentity.Impersonate(token))
                {
                    CloseHandle(token);
                    var path = Path.GetDirectoryName(destPath);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(destPath));
                    }
                    try
                    {
                        File.Copy(sourcePath, destPath, true);
                    }
                    catch (Exception ex)
                    {
                        copyStatus = false;
                        throw;
                    }
    
    
                }
    
                return copyStatus;
            }
    
    
    
            public static bool CopyFileByteArray(byte[] sourceFileByteArray, string destPath)
            {
                bool copyStatus = true;
                IntPtr token = IntPtr.Zero;
                bool isValid = LogonUser(_userName,
                                        _domain,
                                        _password,
                                        (int)LogonType.Interactive,
                                        (int)LogonProvider.Default,
                                        ref token);
                if (!isValid)
                {
                    copyStatus = false;
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new System.ComponentModel.Win32Exception(errorCode);
                }
    
                using (WindowsImpersonationContext UserContext = WindowsIdentity.Impersonate(token))
                {
                    CloseHandle(token);
                    var path = Path.GetDirectoryName(destPath);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(destPath));
                    }
                    try
                    {
                        File.WriteAllBytes(destPath, sourceFileByteArray);
                    }
                    catch (Exception ex)
                    {
                        copyStatus = false;
                        throw;
                    }
    
    
                }
    
                return copyStatus;
            }
    
    
            /// <summary>
            /// 
            /// </summary>
            /// <param name="sourcePath"></param>
            /// <returns></returns>
            public static byte[] FileToByteArray(string sourcePath)
            {
                byte[] fileToByte;
                IntPtr token = IntPtr.Zero;
                bool isValid = LogonUser(_userName,
                                        _domain,
                                        _password,
                                        (int)LogonType.Interactive,
                                        (int)LogonProvider.Default,
                                        ref token);
                if (!isValid)
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new System.ComponentModel.Win32Exception(errorCode);
                }
    
                using (WindowsImpersonationContext UserContext = WindowsIdentity.Impersonate(token))
                {
                    CloseHandle(token);
                    var path = Path.GetDirectoryName(sourcePath);
                    if (!Directory.Exists(path))
                    {
                        throw new System.IO.FileNotFoundException();
                    }
                    try
                    {
                        fileToByte = File.ReadAllBytes(sourcePath);
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }
                return fileToByte;
            }
    
    
    
            /// <summary>
            /// 
            /// </summary>
            /// <param name="sourcePath"></param>
            /// <returns></returns>
            public static bool DeleteFiles(string filePath, string partName, string fileType)
            {
                bool isDeleted=false;
                IntPtr token = IntPtr.Zero;
                bool isValid = LogonUser(_userName,
                                        _domain,
                                        _password,
                                        (int)LogonType.Interactive,
                                        (int)LogonProvider.Default,
                                        ref token);
                if (!isValid)
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new System.ComponentModel.Win32Exception(errorCode);
                }
    
                using (WindowsImpersonationContext UserContext = WindowsIdentity.Impersonate(token))
                {
                    CloseHandle(token);
                    var path = Path.GetDirectoryName(filePath);
                    if (!Directory.Exists(path))
                    {
                        throw new System.IO.FileNotFoundException();
                    }
                    try
                    {
                        var supportFiles = Directory.GetFiles(path)
                        .Where(
                        x => x.ToLower().Contains(partName.ToLower()) && x.ToLower().Contains(fileType.ToLower())
                        ).ToList();
    
                        if (supportFiles.Count>0)
                        {
                            foreach (string supportFile in supportFiles)
                            {
                                File.Delete(supportFile);
                            }
    
                        }
                       
    
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }
                return isDeleted;
            }
    
            /// <summary>
            /// Check the given directory exists
            /// If the directory doesnt exist, then it will be created
            /// </summary>
            /// <param name="destPath"></param>
            /// <returns></returns>
            public static bool CheckOrCreateDir(string destPath)
            {
                bool status = true;
                IntPtr token = IntPtr.Zero;
                bool isValid = LogonUser(_userName,
                                        _domain,
                                        _password,
                                        (int)LogonType.Interactive,
                                        (int)LogonProvider.Default,
                                        ref token);
                if (!isValid)
                {
                    status = false;
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new System.ComponentModel.Win32Exception(errorCode);
                }
    
                using (WindowsImpersonationContext UserContext = WindowsIdentity.Impersonate(token))
                {
                    CloseHandle(token);
                   
                    if (!Directory.Exists(destPath))
                    {
                        try
                        {
                            Directory.CreateDirectory(destPath);
                        }
                        catch (Exception ex)
                        {
                            status = false;
                            throw;
                        }
                    }
                }
                return status;
            }
    
            enum LogonType
            {
                Interactive = 2,
                Network = 3,
                Batch = 4,
                Service = 5,
                Unlock = 7,
                NetworkClearText = 8,
                NewCredentials = 9
            }
    
            enum LogonProvider
            {
                Default = 0,
                WinNT35 = 1,
                WinNT40 = 2,
                WinNT50 = 3
            }
        }
    }
    

    Monday, July 20, 2020 4:03 AM
  • Hi XingYu,

    FYI,

    I tried your code from computer which is not in our domain, but connected to our network via VPN.

    its giving the username or password is incorrect.

    its working fine if the the machine is in domain.

    thanks

    Monday, July 20, 2020 4:46 AM