Beispiel #1
0
        public static bool SetNetworkRequirements(string Port, string FilePort, string OldPort, string OldFilePort)
        {
            string BatchFile = Path.Combine(System.IO.Path.GetTempPath(), "NetworkConfig.bat");
            int exitCode = -1;
            Process proc = new Process();

            proc.StartInfo.FileName = "cmd.exe";
            proc.StartInfo.Arguments = String.Format(@"/c {0}", BatchFile);
            proc.StartInfo.Verb = "runas";
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.StartInfo.UseShellExecute = true;

            try
            {
                StreamWriter BatchFileStream = new StreamWriter(BatchFile);

                //Cleanup previous
                try
                {
                    BatchFileStream.CleanUpDefaultPortsInNetSh(new[] {int.Parse(OldPort), int.Parse(OldFilePort)});
                    BatchFileStream.WriteLine("netsh advfirewall firewall delete rule name=\"JMM Server - Client Port\"");
                    BatchFileStream.WriteLine("netsh advfirewall firewall delete rule name=\"JMM Server - File Port\"");
                    BatchFileStream.WriteLine(
                        $@"netsh advfirewall firewall add rule name=""JMM Server - Client Port"" dir=in action=allow protocol=TCP localport={Port}");
                    Paths.ForEach(a => BatchFileStream.NetSh(a, "add", Port));
                    BatchFileStream.WriteLine(
                        $@"netsh advfirewall firewall add rule name=""JMM Server - File Port"" dir=in action=allow protocol=TCP localport={FilePort}");
                    BatchFileStream.NetSh("", "add", FilePort);
                }
                finally
                {
                    BatchFileStream.Close();
                }

                proc.Start();
                proc.WaitForExit();
                exitCode = proc.ExitCode;
                proc.Close();
                File.Delete(BatchFile);
                if (exitCode != 0)
                {
                    logger.Error("Temporary batch process for netsh and firewall settings returned error code: " + exitCode);
                    return false;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, ex.ToString());
                return false;
            }

            logger.Info("Network requirements set.");

            return true;
        }