Copy file to network path using Windows Service using cmd file

依然范特西╮ 提交于 2019-12-12 03:07:27

问题


I am trying to copy the xml file from the local folder to shared path using C# code in my Windows Service.

It is calling the CMD file and returns Access Denied. But same is works if I try copying to local.

private void CopyFile(string path)
    {
        try
        {

            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();                
            startInfo.UseShellExecute = false;
            startInfo.FileName = Path.Combine(Environment.CurrentDirectory, "Batch", "Run.cmd");
            startInfo.Arguments = "/c " + path;                               
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardOutput = true;

            process = Process.Start(startInfo);
            process.WaitForExit();
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd(); // ACCESS DENIED
            int  exitCode = process.ExitCode; // 1


            process.Close();

        }
        catch (Exception ex)
        {
            string x = ex.Message;
        }
    }

Run.cmd

@set sourcePath=%1

copy /y %sourcePath%\MyTest.xml \\networksharedPath\XML\MyTest.xml

The Windows service's project installer has configured to use LocalSystem Account.

How to make the service to copy the file from local folder to shared machine? Any issues with the C# code or Windows Process Installer configuration?

Note: Manually clicking the cmd file copies to the shared folder. If I modify as Network Service and run I get same error Access is Denied. Tried configuring steps given in https://stackoverflow.com/a/11983513/1559213 But no luck..


回答1:


LocalSystem Account normally does not have access to network shares by default. Try to run the service under your account. By manually running the cmd file it does run under your account and not under LocalSystem account. It will not throw any exceptions while it run as own process. So possibly you can as well trace console output here.



来源:https://stackoverflow.com/questions/34588909/copy-file-to-network-path-using-windows-service-using-cmd-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!