简体   繁体   中英

Copy file to network path using Windows Service using cmd file

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..

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM