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