Page 84 - CSharp/C#
P. 84

Chapter 4: Access network shared folder with


        username and password




        Introduction



        Accessing network share file using PInvoke.


        Examples



        Code to access network shared file


          public class NetworkConnection : IDisposable
             {
                 string _networkName;

                 public NetworkConnection(string networkName,
                     NetworkCredential credentials)
                 {
                     _networkName = networkName;

                     var netResource = new NetResource()
                     {
                         Scope = ResourceScope.GlobalNetwork,
                         ResourceType = ResourceType.Disk,
                         DisplayType = ResourceDisplaytype.Share,
                         RemoteName = networkName
                     };

                     var userName = string.IsNullOrEmpty(credentials.Domain)
                         ? credentials.UserName
                         : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);

                     var result = WNetAddConnection2(
                         netResource,
                         credentials.Password,
                         userName,
                         0);

                     if (result != 0)
                     {
                         throw new Win32Exception(result);
                     }
                 }

             ~NetworkConnection()
             {
                 Dispose(false);
             }

             public void Dispose()
             {
                 Dispose(true);
                 GC.SuppressFinalize(this);



        https://riptutorial.com/                                                                               30
   79   80   81   82   83   84   85   86   87   88   89