81 lines
2.1 KiB
C#
81 lines
2.1 KiB
C#
using System.Runtime.InteropServices;
|
|
using System.Security;
|
|
|
|
public class NetworkAccessService
|
|
{
|
|
private readonly IConfiguration _config;
|
|
|
|
public NetworkAccessService(IConfiguration config)
|
|
{
|
|
_config = config;
|
|
}
|
|
|
|
public void ConnectToNetworkShare(string networkPath)
|
|
{
|
|
var username = _config["NetworkCredentials:ImageServer:Username"];
|
|
var password = _config["NetworkCredentials:ImageServer:Password"];
|
|
var domain = _config["NetworkCredentials:ImageServer:Domain"] ?? ".";
|
|
|
|
var netResource = new NetResource
|
|
{
|
|
Scope = ResourceScope.GlobalNetwork,
|
|
ResourceType = ResourceType.Disk,
|
|
RemoteName = networkPath
|
|
};
|
|
|
|
var result = WNetAddConnection2(netResource, password, username, 0);
|
|
if (result != 0)
|
|
{
|
|
throw new Exception($"Failed to connect to {networkPath}. Error code: {result}");
|
|
}
|
|
}
|
|
|
|
public void DisconnectFromNetworkShare(string networkPath)
|
|
{
|
|
WNetCancelConnection2(networkPath, 0, true);
|
|
}
|
|
|
|
[StructLayout(LayoutKind.Sequential)]
|
|
private 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;
|
|
}
|
|
|
|
private enum ResourceScope : int
|
|
{
|
|
Connected = 1,
|
|
GlobalNetwork = 2,
|
|
Remembered = 3,
|
|
}
|
|
|
|
private enum ResourceType : int
|
|
{
|
|
Any = 0,
|
|
Disk = 1,
|
|
Print = 2,
|
|
}
|
|
|
|
private enum ResourceDisplayType : int
|
|
{
|
|
Generic = 0x0,
|
|
Domain = 0x01,
|
|
Server = 0x02,
|
|
Share = 0x03,
|
|
File = 0x04,
|
|
Group = 0x05,
|
|
}
|
|
|
|
[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);
|
|
}
|