千家信息网

C#如何创建及访问网络硬盘

发表于:2024-10-28 作者:千家信息网编辑
千家信息网最后更新 2024年10月28日,这篇文章将为大家详细讲解有关C#如何创建及访问网络硬盘,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。在某些场景下我们需要远程访问共享硬盘空间,从而实现方便快捷的访问
千家信息网最后更新 2024年10月28日C#如何创建及访问网络硬盘

这篇文章将为大家详细讲解有关C#如何创建及访问网络硬盘,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

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

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

static public WebNetHelper wnh=null;private string remoteHost;//远程主机的共享磁盘,形式如\\1.1.1.1\ccprivate 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文件内容的第一行。

/// /// 测试函数,测试使用该类/// 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#如何创建及访问网络硬盘"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

0