C#创建及访问网络硬盘

在某些场景下我们需要远程访问共享硬盘空间,从而实现方便快捷的访问远程文件。比如公司局域网内有一台电脑存放了大量的文件,其它电脑想要访问该电脑的文件,就可以通过网络硬盘方式实现,跟访问本地硬盘同样的操作,很方便且快速。通过C#我们可以实现网络硬盘的自动化管理。

创建一个类WebNetHelper,在类中加入如下成员变量及成员函数,

static public WebNetHelper wnh=null;
private string remoteHost;//远程主机的共享磁盘,形式如\\1.1.1.1\cc
private string destionDisk;//要访问的磁盘盘符
private string remoteUserName;//登录远程主机的用户名
private string passWord;//登录远程主机的密码

访问网络硬盘,

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;
	}
}

断开网络映射,

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命令,

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文件内容的第一行。

/// <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);
	}
}
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据之道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值