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
}
}

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