1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| [StructLayout(LayoutKind.Sequential)] public class NETRESOURCE { public int dwScope = 0; public int dwType = 0; public int dwDisplayType = 0; public int dwUsage = 0; public string lpLocalName = null; public string lpRemoteName = null; public string lpComment = null; public string lpProvider = null; }
[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);
private static void TestMethod() { string remotePath = @"\\127.0.0.1\20240603"; string username = "Administrator"; string password = "123456";
DisconnectFromRemote(remotePath);
int result = ConnectToRemote(remotePath, username, password);
if (result == 0) { Console.WriteLine("Connected to remote folder successfully.");
string filePath = Path.Combine(remotePath, "test.txt"); if (File.Exists(filePath)) { string content = File.ReadAllText(filePath); Console.WriteLine($"Content of {filePath}:"); Console.WriteLine(content); } else { Console.WriteLine($"File {filePath} does not exist."); }
string newFilePath = Path.Combine(remotePath, "newfile.txt"); File.WriteAllText(newFilePath, "Hello, world!"); Console.WriteLine($"File {newFilePath} created.");
DisconnectFromRemote(remotePath); } else { Console.WriteLine($"Failed to connect to remote folder. Error code: {result}"); } }
private static int ConnectToRemote(string remotePath, string username, string password) { NETRESOURCE netResource = new NETRESOURCE { dwType = 1, lpRemoteName = remotePath };
int result = WNetAddConnection2(netResource, password, username, 0);
return result; }
private static void DisconnectFromRemote(string remotePath) { int result = WNetCancelConnection2(remotePath, 0, true);
if (result == 0) { Console.WriteLine("Disconnected from remote folder successfully."); } else { Console.WriteLine($"Failed to disconnect from remote folder. Error code: {result}"); } }
|