How To Access Network Drive Using C#

In this post, we will learn about how to access a Network folder (drive) using C# code. For accessing network drive we are using NetworkCredential and MPR library for accessing files and directory of network folder. For accessing  network drive we have to pass network path and its username and password for connecting with the network then we can access files and directory inside network drive. Let's start coding.
 
Create one class file name that ConnectToSharedFolder and add below namespaces for access Network Credential and MPR library methods.
  1. using System;  
  2. using System.ComponentModel;  
  3. using System.Runtime.InteropServices;  
  4. using System.Net; 
 Write the below code in ConnectToSharedFolder class file and inherit this class file with IDisposable -- see the below code.
  1. public class ConnectToSharedFolder: IDisposable  
  2. {  
  3.     readonly string _networkName;  
  4.   
  5.     public ConnectToSharedFolder(string networkName, NetworkCredential credentials)  
  6.     {  
  7.         _networkName = networkName;  
  8.   
  9.         var netResource = new NetResource  
  10.         {  
  11.             Scope = ResourceScope.GlobalNetwork,  
  12.             ResourceType = ResourceType.Disk,  
  13.             DisplayType = ResourceDisplaytype.Share,  
  14.             RemoteName = networkName  
  15.         };  
  16.   
  17.         var userName = string.IsNullOrEmpty(credentials.Domain)  
  18.             ? credentials.UserName  
  19.             : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);  
  20.   
  21.         var result = WNetAddConnection2(  
  22.             netResource,  
  23.             credentials.Password,  
  24.             userName,  
  25.             0);  
  26.   
  27.         if (result != 0)  
  28.         {  
  29.             throw new Win32Exception(result, "Error connecting to remote share");  
  30.         }  
  31.     }  
  32.   
  33.     ~ConnectToSharedFolder()  
  34.     {  
  35.         Dispose(false);  
  36.     }  
  37.   
  38.     public void Dispose()  
  39.     {  
  40.         Dispose(true);  
  41.         GC.SuppressFinalize(this);  
  42.     }  
  43.   
  44.     protected virtual void Dispose(bool disposing)  
  45.     {  
  46.         WNetCancelConnection2(_networkName, 0, true);  
  47.     }  
  48.   
  49.     [DllImport("mpr.dll")]  
  50.     private static extern int WNetAddConnection2(NetResource netResource,  
  51.         string password, string username, int flags);  
  52.   
  53.     [DllImport("mpr.dll")]  
  54.     private static extern int WNetCancelConnection2(string name, int flags,  
  55.         bool force);  
  56.   
  57.     [StructLayout(LayoutKind.Sequential)]  
  58.     public class NetResource  
  59.     {  
  60.         public ResourceScope Scope;  
  61.         public ResourceType ResourceType;  
  62.         public ResourceDisplaytype DisplayType;  
  63.         public int Usage;  
  64.         public string LocalName;  
  65.         public string RemoteName;  
  66.         public string Comment;  
  67.         public string Provider;  
  68.     }  
  69.   
  70.     public enum ResourceScope : int  
  71.     {  
  72.         Connected = 1,  
  73.         GlobalNetwork,  
  74.         Remembered,  
  75.         Recent,  
  76.         Context  
  77.     };  
  78.   
  79.     public enum ResourceType : int  
  80.     {  
  81.         Any = 0,  
  82.         Disk = 1,  
  83.         Print = 2,  
  84.         Reserved = 8,  
  85.     }  
  86.   
  87.     public enum ResourceDisplaytype : int  
  88.     {  
  89.         Generic = 0x0,  
  90.         Domain = 0x01,  
  91.         Server = 0x02,  
  92.         Share = 0x03,  
  93.         File = 0x04,  
  94.         Group = 0x05,  
  95.         Network = 0x06,  
  96.         Root = 0x07,  
  97.         Shareadmin = 0x08,  
  98.         Directory = 0x09,  
  99.         Tree = 0x0a,  
  100.         Ndscontainer = 0x0b  
  101.     }  

After adding the above code in class file see the below code for how to call this method outside of class.

Declare below variables for accessing network drive.

  1. public string networkPath = @"\\{Your IP or Folder Name of Network}\Shared Data";  
  2. NetworkCredential credentials = new NetworkCredential(@"{User Name}""{Password}");  
  3. public string myNetworkPath = string.Empty; 
 Upload File
  1. public Void FileUpload(string UploadURL)  
  2. {  
  3.     try  
  4.     {  
  5.         using (new ConnectToSharedFolder(networkPath, credentials))  
  6.         {  
  7.             var fileList = Directory.GetDirectories(networkPath);  
  8.   
  9.             foreach (var item in fileList) { if (item.Contains("{ClientDocument}")) { myNetworkPath = item; } }  
  10.   
  11.             myNetworkPath = myNetworkPath + UploadURL;  
  12.   
  13.             using (FileStream fileStream = File.Create(UploadURL, file.Length))  
  14.             {  
  15.                 await fileStream.WriteAsync(file, 0, file.Length);  
  16.                 fileStream.Close();  
  17.             }  
  18.         }  
  19.     }  
  20.     catch (Exception ex)  
  21.     {  
  22.                       
  23.     }  
  24.   
  25.     return obj;  

The above function uploads file in network drive using ConnectToSharedFolder. For this class we have to pass network path and username and password for accessing network then get the specific folder from the network and create a file inside the folder using FileStream.
 
Download File
  1. public byte[] DownloadFileByte(string DownloadURL)  
  2. {  
  3.     byte[] fileBytes = null;  
  4.   
  5.     using (new ConnectToSharedFolder(networkPath, credentials))  
  6.     {  
  7.         var fileList = Directory.GetDirectories(networkPath);  
  8.   
  9.         foreach (var item in fileList) { if (item.Contains("ClientDocuments")) { myNetworkPath = item; } }  
  10.   
  11.         myNetworkPath = myNetworkPath + DownloadURL;  
  12.   
  13.         try  
  14.         {  
  15.             fileBytes = File.ReadAllBytes(myNetworkPath);  
  16.         }  
  17.         catch (Exception ex)  
  18.         {  
  19.             string Message = ex.Message.ToString();  
  20.         }  
  21.     }  
  22.   
  23.     return fileBytes;  

The above function downloads the file from network drive using ConnectToSharedFolder class by passing network path and username and password for accessing network drive. This function reads bytes of the file using File.ReadAllBytes().
 
Note
Adding this code is compulsory for reading and writing files in the network drive.
  1. using(new ConnectToSharedFolder(networkPath, credentials)) {}