Introduction
In this post, we will learn about how to access a Network folder (drive) using C# code. For accessing the network drive, we are using NetworkCredential and MPR library for accessing files and the directory of the network folder. To access the network drive, we have to pass the network path and its username and password for connecting with the network. Then, we can access files and directories inside the network drive. Let's start coding.
Create one class file name that ConnectToSharedFolder and add the below namespaces for access to Network Credential and MPR library methods.
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Net;
Write the below code in the ConnectToSharedFolder class file and inherit this class file with IDisposable -- see the below code.
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Net;
public class ConnectToSharedFolder : IDisposable
{
private 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
: $@"{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 the class file, see the below code for how to call this method outside of class.
Declare the below variables for accessing the 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)
{
// Handle the exception (e.g., log it or take appropriate action)
}
// It's unclear where `obj` is coming from; make sure it's defined and return it.
return obj;
}
The above function uploads files in the network drive using ConnectToSharedFolder. For this class, we have to pass the network path and username and password for accessing the 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();
// Handle the exception (e.g., log it or take appropriate action)
}
}
return fileBytes;
}
The above function downloads the file from the network drive using ConnectToSharedFolder class by passing the network path and username and password for accessing the 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)) {}

Mohamed HassanPosted Mar 4, 2023, 1:39 PM
Var result return 67 , then throw exception why ??
Bebins VPosted Aug 1, 2021, 2:06 PM
Hi Team, This is not the best way. It will not work most of the time. If you want to connect a network/shared drive from the application then you need to create a virtual directory for that.
Sonu MauryaPosted Jun 24, 2021, 2:48 PM
Sometime working fine and sometime generate error - System.ComponentModel.Win32Exception: Error connecting to remote share
Timothy VvvPosted Mar 9, 2021, 2:41 PM
Thx for the helpful piece of code, however IMHO better to use NuGet instead of dll import, so just for comparison, using mpr.dll NuGet https://github.com/dahall/Vanara/blob/master/PInvoke/Mpr/CorrelationReport.md: using System; using System.ComponentModel; using static Vanara.PInvoke.Mpr; namespace MyNamespace { internal class SharedFolderConnector : IDisposable { private readonly string remoteName; internal SharedFolderConnector(string remoteName, string login, string password) { this.remoteName = remoteName; var netResource = new NETRESOURCE(remoteName); var result = WNetAddConnection2( netResource, password, login, 0); if (result != 0) { throw new Win32Exception(Convert.ToInt32(result.ToString()), "Error connecting to remote share"); } } ~SharedFolderConnector() { this.Dispose(false); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { WNetCancelConnection2(this.remoteName, 0, true); } } }
Omid KaramiPosted Feb 11, 2021, 2:06 AM
It fixed my problem, really appreciate.
Riza AfandiPosted Jan 20, 2021, 4:50 AM
Hi, im getting error 'Access to the path ,,, is denied. What should I do ?'
Rahul SolankiPosted Dec 16, 2020, 9:24 AM
I'm getting error code 1219,1920 while connecting to network drive. anyone know this error?
ALSHIMA ALDEAIJPosted Oct 18, 2020, 2:50 PM
Thank you!
Prashant SrivastavaPosted Aug 19, 2020, 8:32 AM
Do i need to add reference to this mpr.dll in my Web API in order to use it. I do not see the dll though. Where can we get this from ? Also, do we need to make any changes in IIS APP pool for this ?
sivanarayanareddy mittaPosted Jun 18, 2020, 6:05 AM
Result 67 is coming from ConnectToSharedFolder constuctor,So it's coming to catch part,i think its may be because of "mpr.dll".Can you tell how u got the mpr.dll
Priyanshu SaxenaPosted Jun 12, 2020, 2:47 AM
'result' in ConnectToSharedFolder coming as 67 instead of 0. Any clue why its failing?
Krzysztof SPosted Aug 28, 2019, 4:11 AM
How can I add progress bar to file upload?
Robert KoernkePosted Jan 1, 2019, 7:32 AM
The upload and download pieces of code. Need serious modification. 'file' is not declared. obj is not declared. It's pretty disjointed. I think its a start in the right direction, but not finished.
Filip BłaszczykPosted Oct 31, 2018, 5:01 AM
Really helpful. Thanks!
Viknaraj ManogararajahPosted Jul 19, 2018, 6:36 AM
Nice Article...........
Hardik DeshaniPosted Jul 8, 2018, 9:23 AM
Thank you sir
Ravishankar NPosted Jul 8, 2018, 3:16 AM
Nicely written