在某些场景下我们需要远程访问共享硬盘空间,从而实现方便快捷的访问远程文件。比如公司局域网内有一台电脑存放了大量的文件,其它电脑想要访问该电脑的文件,就可以通过网络硬盘方式实现,跟访问本地硬盘同样的操作,很方便且快速。通过C#我们可以实现网络硬盘的自动化管理。
创建一个类WebNetHelper,在类中加入如下成员变量及成员函数,
1
2
3
4
5
|
static public WebNetHelper wnh= null ; private string remoteHost; //远程主机的共享磁盘,形式如\\1.1.1.1\cc private string destionDisk; //要访问的磁盘盘符 private string remoteUserName; //登录远程主机的用户名 private string passWord; //登录远程主机的密码 |
访问网络硬盘,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public bool Connect() { try { string cmdString = string .Format( @"net use {1}: {0} {3} /user:{2} >NUL" , this .RemoteHost, this .DestionDisk, this .RemoteUserName, this .PassWord); this .WriteStringToComman(cmdString); return true ; } catch (Exception e) { throw e; } } |
断开网络映射,
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public bool Disconnect() { try { string cmdString= string .Format( @"net use {0}: /delete >NUL" , this .DestionDisk); this .WriteStringToComman(cmdString); return true ; } catch (Exception e) { throw e; } } |
执行CMD命令,
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
|
private bool WriteStringToComman( string cmdString) { bool Flag = true ; Process proc = new Process(); proc.StartInfo.FileName = "cmd.exe" ; proc.StartInfo.UseShellExecute = false ; proc.StartInfo.RedirectStandardInput = true ; proc.StartInfo.RedirectStandardOutput = true ; proc.StartInfo.RedirectStandardError = true ; proc.StartInfo.CreateNoWindow = true ; try { proc.Start(); string command = cmdString; proc.StandardInput.WriteLine(command); command = "exit" ; proc.StandardInput.WriteLine(command); while (proc.HasExited == false ) { proc.WaitForExit(1000); } string errormsg = proc.StandardError.ReadToEnd(); if (errormsg != "" ) Flag = false ; proc.StandardError.Close(); return Flag; } catch (Exception e) { throw e; } finally { proc.Close(); proc.Dispose(); } } |
然后test函数为测试使用的过程。\\1.1.1.1\cc为网络硬盘地址,K为要映射的盘符,"Noner"为远程主机的登录名,"uiosdsau"为远程主机的密码。Test函数为读取网络硬盘下的ImbaMallLog.txt文件内容的第一行。
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
|
/// <summary> /// 测试函数,测试使用该类 /// </summary> private void test() { try { if (!Directory.Exists( @"K:\" )) { WebNetHelper.wnh = new WebNetHelper( @"\\1.1.1.1\cc" , "K" , "Noner" , "uiosdsau" ); WebNetHelper.wnh.Connect(); } StreamReader sr = new StreamReader( @"K:\ImbaMallLog.txt" ); string tt = sr.ReadLine(); //MessageBox.Show(tt); sr.Close(); sr.Dispose(); if (WebNetHelper.wnh != null ) { WebNetHelper.wnh.Disconnect(); } } catch (Exception e) { //MessageBox.Show(e.Message); } } |
到此这篇关于C#创建及访问网络硬盘的实现的文章就介绍到这了,更多相关C# 访问网络硬盘内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/huzhizhewudi/article/details/123614310