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.
- using System;
- using System.ComponentModel;
- using System.Runtime.InteropServices;
- using System.Net;
Write the below code in ConnectToSharedFolder class file and inherit this class file with IDisposable -- see the below code.
- public class ConnectToSharedFolder: IDisposable
- {
- readonly string _networkName;
-
- public ConnectToSharedFolder(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, "Error connecting to remote share");
- }
- }
-
- ~ConnectToSharedFolder()
- {
- Dispose(false);
- }
-
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- protected virtual void Dispose(bool disposing)
- {
- WNetCancelConnection2(_networkName, 0, true);
- }
-
- [DllImport("mpr.dll")]
- private static extern int WNetAddConnection2(NetResource netResource,
- string password, string username, int flags);
-
- [DllImport("mpr.dll")]
- private static extern int WNetCancelConnection2(string name, int flags,
- bool force);
-
- [StructLayout(LayoutKind.Sequential)]
- public class NetResource
- {
- public ResourceScope Scope;
- public ResourceType ResourceType;
- public ResourceDisplaytype DisplayType;
- public int Usage;
- public string LocalName;
- public string RemoteName;
- public string Comment;
- public string Provider;
- }
-
- public enum ResourceScope : int
- {
- Connected = 1,
- GlobalNetwork,
- Remembered,
- Recent,
- Context
- };
-
- public enum ResourceType : int
- {
- Any = 0,
- Disk = 1,
- Print = 2,
- Reserved = 8,
- }
-
- public enum ResourceDisplaytype : int
- {
- Generic = 0x0,
- Domain = 0x01,
- Server = 0x02,
- Share = 0x03,
- File = 0x04,
- Group = 0x05,
- Network = 0x06,
- Root = 0x07,
- Shareadmin = 0x08,
- Directory = 0x09,
- Tree = 0x0a,
- Ndscontainer = 0x0b
- }
- }
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.
- public string networkPath = @"\\{Your IP or Folder Name of Network}\Shared Data";
- NetworkCredential credentials = new NetworkCredential(@"{User Name}", "{Password}");
- public string myNetworkPath = string.Empty;
Upload File
- public Void FileUpload(string UploadURL)
- {
- try
- {
- using (new ConnectToSharedFolder(networkPath, credentials))
- {
- var fileList = Directory.GetDirectories(networkPath);
-
- foreach (var item in fileList) { if (item.Contains("{ClientDocument}")) { myNetworkPath = item; } }
-
- myNetworkPath = myNetworkPath + UploadURL;
-
- using (FileStream fileStream = File.Create(UploadURL, file.Length))
- {
- await fileStream.WriteAsync(file, 0, file.Length);
- fileStream.Close();
- }
- }
- }
- catch (Exception ex)
- {
-
- }
-
- 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
- public byte[] DownloadFileByte(string DownloadURL)
- {
- byte[] fileBytes = null;
-
- using (new ConnectToSharedFolder(networkPath, credentials))
- {
- var fileList = Directory.GetDirectories(networkPath);
-
- foreach (var item in fileList) { if (item.Contains("ClientDocuments")) { myNetworkPath = item; } }
-
- myNetworkPath = myNetworkPath + DownloadURL;
-
- try
- {
- fileBytes = File.ReadAllBytes(myNetworkPath);
- }
- catch (Exception ex)
- {
- string Message = ex.Message.ToString();
- }
- }
-
- 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.
- using(new ConnectToSharedFolder(networkPath, credentials)) {}
![Listen to the translation]()
how to call this above class method outside of class.
Declare below variables for access network drive.
| | | | | | | | | |
![Listen to the translation]()
how to call this above class method outside of class.
Declare below variables for access network drive.
Text-to-speech function is limited to 200 characters