| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- using System;
- using System.Runtime.InteropServices;
- namespace LAPS_XMLQC_Service.App_Data
- {
- public class NetworkShareUtility
- {
- [DllImport("mpr.dll")]
- private static extern int WNetAddConnection2(ref 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)]
- private struct NETRESOURCE
- {
- public int dwScope;
- public int dwType;
- public int dwDisplayType;
- public int dwUsage;
- public string lpLocalName;
- public string lpRemoteName;
- public string lpComment;
- public string lpProvider;
- }
- public static void ConnectToShare(string uncPath, string username, string password)
- {
- var netResource = new NETRESOURCE
- {
- dwType = 1, // RESOURCETYPE_DISK
- lpRemoteName = uncPath
- };
- // flags=0 → create connection
- int result = WNetAddConnection2(ref netResource, password, username, 0);
- if (result != 0 && result != 1219) // 1219 = already connected
- {
- throw new Exception($"Error connecting to remote share. Error code: {result}");
- }
- }
- public static void DisconnectFromShare(string uncPath)
- {
- WNetCancelConnection2(uncPath, 0, true);
- }
- }
- }
|