在C#程式中访问网络路径

本文最后更新于:2024年7月2日 晚上

程序内如何访问网络路径

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
// 定义NETRESOURCE结构
[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;
}

// P/Invoke声明WNetAddConnection2方法
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2(NETRESOURCE netResource, string password, string username, int flags);

// P/Invoke声明WNetCancelConnection2方法
[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, // 1 表示DISK驱动器
lpRemoteName = remotePath
};

// 调用WNetAddConnection2连接
int result = WNetAddConnection2(netResource, password, username, 0);

return result;
}

// 方法:断开与远程共享文件夹的连接
private static void DisconnectFromRemote(string remotePath)
{
// 调用WNetCancelConnection2断开连接
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}");
}
}

这里有一只爱丽丝

希望本文章能够帮到您~


在C#程式中访问网络路径
https://map1e-g.github.io/2024/07/02/CSharp-Connect2Remote/
作者
MaP1e-G
发布于
2024年7月2日
许可协议