using System; using System.IO; using System.Runtime.InteropServices; using System.Text; public class NetworkShareAccess : IDisposable { private readonly string _networkPath; private readonly string _username; private readonly string _password; // Constructor to initialize the network path, username, and password public NetworkShareAccess(string networkPath, string username, string password) { _networkPath = networkPath; _username = username; _password = password; } // Public method to connect to the network path public void ConnectToNetworkPath() { var netResource = new NetResource { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, DisplayType = ResourceDisplayType.Share, RemoteName = _networkPath }; var result = WNetAddConnection2(netResource, _password, _username, 0);// if (result != 0) { Console.WriteLine($"Error connecting to network path: {result}"); throw new IOException($"Error connecting to network path: {result}"); } } // Public method to disconnect from the network share public void DisconnectFromNetworkShare() { // Check if the network path is connected var buffer = new StringBuilder(512); int bufferSize = buffer.Capacity; int connectionStatus = WNetGetConnection(_networkPath, buffer, ref bufferSize); if (connectionStatus != 0) { Console.WriteLine($"Network path {_networkPath} is not connected. Skipping disconnection."); return; // Exit if the connection does not exist } // Proceed with disconnection var result = WNetCancelConnection2(_networkPath, 0, true); if (result != 0) { throw new IOException($"Error disconnecting from network path: {result}"); } } // Dispose method to ensure proper cleanup public void Dispose() { DisconnectFromNetworkShare(); } // P/Invoke for adding a network connection [DllImport("mpr.dll")] private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flags); // P/Invoke for canceling a network connection [DllImport("mpr.dll")] private static extern int WNetCancelConnection2(string name, int flags, bool force); // P/Invoke for checking if a network connection exists [DllImport("mpr.dll")] private static extern int WNetGetConnection(string localName, StringBuilder remoteName, ref int length); // Struct for network resource [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; } // Enum for resource scope private enum ResourceScope { Connected = 1, GlobalNetwork, Remembered, Recent, Context } // Enum for resource type private enum ResourceType { Any = 0, Disk = 1, Print = 2, Reserved = 8 } // Enum for resource display type private enum ResourceDisplayType { Generic = 0x0, Domain = 0x01, Server = 0x02, Share = 0x03, File = 0x04, Group = 0x05 } }