.Net 服务(WCF) 中访问共享文件

原理:在就先使用CMD命令创建空连接,就可以使用服务方式进行访问.

    /// <summary>
    /// net use 建立映射的功能模块
    /// </summary>
    public static class NetUseHelper
    {
        public static IpcWcfOperateResult CreateConnect(string dosLine)
        {
            IpcWcfOperateResult rlt = new IpcWcfOperateResult() { isSuccess = false };
            Process proc = new Process();
            try
            {
                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;
                proc.Start();

                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }

                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (String.IsNullOrEmpty(errormsg))
                {
                    rlt.isSuccess = true;
                }
                else
                {
                    rlt.isSuccess = false;
                    rlt.errorMesg = errormsg;
                }
            }
            catch (Exception ex)
            {
                rlt.isSuccess = false;
                rlt.errorMesg = ex.Message;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return rlt;
        }
    }
        public IpcWcfOperateResult CheckAndCreateConnect()
        {
            string dosLine = AppSettings.GetSetting("NetworkShare");
            if (!string.IsNullOrEmpty(dosLine))
            {
                return NetUseHelper.CreateConnect(dosLine);
            }
            else
            {
                return new IpcWcfOperateResult
                {
                    isSuccess = false,
                    errorMesg = "本地数据库模式不需要创建连接",
                    model = "Local"
                };
            }
        }

web.config中配置命令行

  <appSettings>
    <!-- net use \{IP地址或计算机名}{共享目录相对路径} /User:{电脑用户名} {密码} /PERSISTENT:YES -->
    <add key="NetworkShare" value="net use \192.168.1.161share /User:Administrator /PERSISTENT:YES"/>
  </appSettings>

如果报错:

不允许一个用户使用一个以上用户名与服务器或共享资源的多重连接。中断与此服务器或共
享资源的所有连接,然后再试一次。
使用命令删除一下连接,先删除所有连接:

net use * /del /y

原文地址:https://www.cnblogs.com/sky-gfan/p/8276690.html