Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I tried running a bat file on a network server, but when i debug it it throws an error that UNC paths are not supported, i have tried running the bat file on local system it works fine but not on network server
what should I do?
thanks in advance.

I m attaching my code below.
Service1.cs

public partial class Service1 : ServiceBase
   {
       private Timer timer1 = null;

       public Service1()
       {
           InitializeComponent();
       }

       protected override void OnStart(string[] args)
       {
           timer1 = new Timer();
           this.timer1.Interval = 60000; //60 sec
           this.timer1.Elapsed +=new System.Timers.ElapsedEventHandler(this.timer1_Tick);
           timer1.Enabled=true;
           Library.WriteErrorLog("test windows service started");
           var result = RunProcess(@"\\192.168.124.30\IT\WebCommon\webfolder" /*the network path*/, "webupknvp.Bat", "cmd.exe", false);
                                  // my path C:\Abhay\batfile
           if (result == 0)
           {
               // success
               Console.WriteLine("Sucess");
           }
           else
           {
               // failed ErrorLevel / app ExitCode
               Console.WriteLine("failed try again");

           }


       }

       protected override void OnStop()
       {
           timer1.Enabled = false;
           Library.WriteErrorLog("Test Service ended");
       }

       public void timer1_Tick(object sender, ElapsedEventArgs e)
       {
           //job
       /*   var result = RunProcess(@"C:\Abhay\batfile", "webupknvp.Bat", "", false);
           if (result == 0)
           {
               // success
               Console.WriteLine("Sucess");
           }
           else
           {
               // failed ErrorLevel / app ExitCode
               Console.WriteLine("failed try again");

           }
       */

       }

       public int RunProcess(string workDir, string appName, string args, bool hide = false)
           {

                  // Process proc = null;
                   Process proc = new Process();
                  // string batrun = string.Format("/c" + @"C:\Abhay\batfile", "cmd.exe"); // or @"C:\Abhay\batfile" in the end ("cmd.exe", "/c" + @"C:\Abhay\batfile")
                   proc.StartInfo.UseShellExecute = false;   //addition
                  args = "/c";
                   appName = "cmd.exe";
                   workDir = @"\\192.168.124.30\IT\WebCommon\webfolder";
                   proc.StartInfo.WorkingDirectory = workDir;//batrun
                   proc.StartInfo.FileName = appName;
                   proc.StartInfo.Arguments = args;
                   proc.StartInfo.CreateNoWindow = hide;

                   proc.Start();
                   proc.WaitForExit();

                   return proc.ExitCode;
              }


Library.cs

public static class Library
   {
       public static void WriteErrorLog(Exception ex)
       {
           StreamWriter sw = null;
           try
           {
               sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\ Logfile.txt", true);
               sw.WriteLine(DateTime.Now.ToString() + ":" + ex.Source.ToString().Trim() + ";" + ex.Message.ToString().Trim());
               sw.Flush();
               sw.Close();

           }
           catch
           {

           }
       }

       public static void WriteErrorLog(string Message)
       {
           StreamWriter sw = null;
           try
           {

               sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\ Logfile.txt", true);
               sw.WriteLine(DateTime.Now.ToString() + ":" + Message);
               sw.Flush();
               sw.Close();
           }
           catch
           {

           }
       }

Program.cs

static void Main(String[] args)
        {
            // Initialize the service to start
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
    { 
        new Service1() 
    };

            // In interactive mode ?
            if (Environment.UserInteractive)
            {
                // In debug mode ?
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    // Simulate the services execution
                    RunInteractiveServices(ServicesToRun);
                }
                else
                {
                    try
                    {
                        bool hasCommands = false;
                        // Having an install command ?
                        if (HasCommand(args, "install"))
                        {
                            ManagedInstallerClass.InstallHelper(new String[] { typeof(Program).Assembly.Location });
                            hasCommands = true;
                            // Having a start command ?
                            if (HasCommand(args, "start"))
                            {
                                foreach (var service in ServicesToRun)
                                {
                                    ServiceController sc = new ServiceController(service.ServiceName);
                                    sc.Start();
                                    sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10));
                                }
                                hasCommands = true;
                            }
                        }
                        // Having a stop command 
                        if (HasCommand(args, "stop"))
                        {
                            foreach (var service in ServicesToRun)
                            {
                                ServiceController sc = new ServiceController(service.ServiceName);
                                sc.Stop();
                                sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10000));// change 
                            }
                            hasCommands = false;
                        }
                        // Having an uninstall command 
                        if (HasCommand(args, "uninstall"))
                        {
                            ManagedInstallerClass.InstallHelper(new String[] { "/u", typeof(Program).Assembly.Location });
                            hasCommands = true;
                            
                            
                        }
                        // If we don't have commands we print usage message
                        if (!hasCommands)
                        {
                            Console.WriteLine("Usage : {0} [command] [command ...]", Environment.GetCommandLineArgs());
                            Console.WriteLine("Commands : ");
                            Console.WriteLine(" - install : Install the services");
                            Console.WriteLine(" - uninstall : Uninstall the services");
                        }
                    }
                    catch (Exception ex)
                    {
                        var oldColor = Console.ForegroundColor;
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Error : {0}", ex.GetBaseException().Message);
                        Console.ForegroundColor = oldColor;
                    }
                }
            }
            else
            {
                // Normal service execution
                ServiceBase.Run(ServicesToRun);
            }
        }

        static void RunInteractiveServices(ServiceBase[] servicesToRun)
        {
            Console.WriteLine();
            Console.WriteLine("Start the services in interactive mode.");
            Console.WriteLine();

            // Get the method to invoke on each service to start it
            MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);

            // Start services loop
            foreach (ServiceBase service in servicesToRun)
            {
                Console.Write("Starting {0} ... ", service.ServiceName);
                onStartMethod.Invoke(service, new object[] { new string[] { } });
                Console.WriteLine("Started");
            }

            // Waiting the end
            Console.WriteLine();
            Console.WriteLine("Press a key to stop services and finish process...");
            Console.ReadKey();
            Console.WriteLine();

            // Get the method to invoke on each service to stop it
            MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);

            // Stop loop
            foreach (ServiceBase service in servicesToRun)
            {
                Console.Write("Stopping {0} ... ", service.ServiceName);
                onStopMethod.Invoke(service, null);
                Console.WriteLine("Stopped");
            }

            Console.WriteLine();
            Console.WriteLine("All services are stopped.");

            // Waiting a key press to not return to VS directly
            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.WriteLine();
                Console.Write("=== Press a key to quit ===");
                Console.ReadKey();
            }
        }
        static bool HasCommand(String[] args, String command)
        {
            if (args == null || args.Length == 0 || String.IsNullOrWhiteSpace(command)) return false;
            return args.Any(a => String.Equals(a, command, StringComparison.OrdinalIgnoreCase));


        }
        
    }
}


What I have tried:

I got stuck here, no idea how to solve this.
Posted
Updated 20-Mar-17 0:55am
v4
Comments
Richard MacCutchan 20-Mar-17 6:45am    
The message is telling you what the problem is, you may not use UNC paths.
r.abhaysinghania 20-Mar-17 6:53am    
okay, is it possible to solve that?
Richard MacCutchan 20-Mar-17 7:04am    
Yes, do not use UNC paths.
[no name] 20-Mar-17 6:53am    
Why are you running cmd to execute a bat file anyway?
r.abhaysinghania 20-Mar-17 6:56am    
a windows service is running a bat file via cmd , now i m trying to make it run on network server.

1 solution

The error message is pretty clear:
CMD.EXE was started with the above path as the current directory UNC paths are not supported defaulting to windows directory

Looking at your code:
workDir = @"\\192.168.124.30\IT\WebCommon\webfolder";
proc.StartInfo.WorkingDirectory = workDir;//batrun
You are specifically trying to start this using a UNC path[^] - \\192.168.124.30
You can't do that.
You may be able to do it if you map a drive letter to the UNC share and access your batch file via that, but be aware that the batch file and applications it starts will still run on your local PC, not on the remote machine.
 
Share this answer
 
Comments
r.abhaysinghania 20-Mar-17 6:59am    
I tried mapping a letter to the unc like this @"Z:\\192.168.124.30\IT\WebCommon\webfolder";
OriginalGriff 20-Mar-17 7:17am    
That isn't a mapped drive:
http://www.laptopmag.com/articles/map-network-drive-windows-10
r.abhaysinghania 20-Mar-17 7:24am    
I already have the mapped drive. named Common(\\192.168.124.30\IT)(X:)
r.abhaysinghania 20-Mar-17 8:26am    
thank you for the help guys... I was searching about the UNC on cmd and found some thing on msdn that cmd does not support UNC.
Richard MacCutchan 20-Mar-17 9:39am    
Which is what I told you two hours ago.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900