.NET CORE Worker Service服务访问服务器共享目录提示无权限
问题:.NET CORE Worker Service中访问服务器共享目录,代码运行时不报错,发布出来后访问共享目录创建文件夹或者文件等所有操作都提示无权限
解决方案:先对共享目录进行连接,然后再进行文件夹或文件创建等操作
bool state = connectState(共享目录路径, 用户名, 密码); if(state) {
//业务逻辑 } /// <summary> /// 连接远程共享文件夹 /// </summary> /// <param name="path">远程共享文件夹的路径</param> /// <param name="userName">用户名</param> /// <param name="passWord">密码</param> private static bool connectState(string path, string userName, string passWord) { var flag = false; var 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(); var dosLine = "net use " + path + " " + passWord + " /user:" + userName; proc.StandardInput.WriteLine(dosLine); proc.StandardInput.WriteLine("exit"); while (!proc.HasExited) { proc.WaitForExit(1000); } var errormsg = proc.StandardError.ReadToEnd(); proc.StandardError.Close(); if (string.IsNullOrEmpty(errormsg)) { flag = true; } else { throw new Exception(errormsg); } } catch (Exception ex) { throw ex; } finally { proc.Close(); proc.Dispose(); } return flag; }