Dispose() protected method

protected Dispose ( bool disposing ) : void
disposing bool
return void
Ejemplo n.º 1
0
        static bool AddFirewallRule()
        {
            //accomplished via shelling out to netsh.exe with relevant arguments.
            Process proc = new Process();
            proc.EnableRaisingEvents = false;
            proc.StartInfo.UseShellExecute = false; //the process should be created directly from this app.
            proc.StartInfo.RedirectStandardError = true; //allowed since we set UseShellExecute to false
            proc.StartInfo.FileName = "netsh.exe"; //would include the folder name if not in system path
            proc.StartInfo.Arguments = "advfirewall firewall add rule name=\"Banned IP Addresses\" dir=in action=block description=\"IPs detected from Security Event Log with more than 10 failed attempts a day\" enable=yes profile=any localip=any protocol=any interfacetype=any";
            proc.StartInfo.CreateNoWindow = true;
            string errstr = "";

            try
            {
                OutputMsg("Starting netsh.exe to add firewall rule");
                proc.Start();
                errstr = proc.StandardError.ReadToEnd();
                proc.WaitForExit();
            }
            catch (Exception e)
            {
                OutputMsg("Unable to add firewall rule. Error starting process for netsh.exe" , e.ToString());
                proc.Dispose();
                return false;
            }

            if (errstr != "")
            {
                OutputMsg("Suspicious output from netsh.exe:\n\t" + errstr +
                                "\n*** Check to verify that the update was processed correctly. ***");
             }

            proc.Dispose();
            return true;
        }
        private XmlDocument RetrieveDataFromSubversion(string subversionArguments)
        {
            var subversionClient = new Process();
            subversionClient.StartInfo.CreateNoWindow = true;
            subversionClient.StartInfo.UseShellExecute = false;
            subversionClient.StartInfo.RedirectStandardOutput = true;
            subversionClient.StartInfo.RedirectStandardInput = true;
            subversionClient.StartInfo.RedirectStandardError = true;

            subversionClient.StartInfo.FileName = _subversionPath;
            subversionClient.StartInfo.Arguments = subversionArguments;

            Console.WriteLine("Starting subversion client...");

            subversionClient.Start();

            Console.WriteLine("Collecting subversion client output...");

            string output = subversionClient.StandardOutput.ReadToEnd();

            subversionClient.WaitForExit();
            subversionClient.Close();
            subversionClient.Dispose();

            Console.WriteLine("Subversion output collected.");

            return new XmlDocument {InnerXml = output};
        }
Ejemplo n.º 3
0
        public void start(IntPtr handleClient, bool checkFile)
        {
            if (started())
                    MessageBox.Show("Já possui um processo aberto do " + file + ".");
            else if(checkFile && !System.IO.File.Exists(file))
                MessageBox.Show("Arquivo " + file + " não encontrado.");
            else if (handleClient != IntPtr.Zero)
            {
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo.FileName = file;

                if (proc.Start())
                {
                    while (true)
                    {
                        process = System.Diagnostics.Process.GetProcessById(proc.Id);
                        if (started())
                        {
                            SetParent(process.MainWindowHandle, handleClient);
                            proc.Dispose();
                            break;
                        }
                        System.Threading.Thread.Sleep(Convert.ToInt32(Enums.Thread.Sleep));
                    }
                }else
                    MessageBox.Show("Não foi possivel executar o processo do " + file + ".");
            }
        }
Ejemplo n.º 4
0
        public Boolean Start()
        {
            //FileInfo commandFile = new FileInfo(_commandFullPath);
            //if(commandFile.Exists == false) throw new FileNotFoundException();

            Boolean result = false;

            Process p = new Process();
            p.StartInfo.FileName = _command;
            if(_arugment.IsNullOrEmpty() == false) p.StartInfo.Arguments = _arugment;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;

            // These two optional flags ensure that no DOS window appears
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.Start();
            p.WaitForExit();
            ErrorMessage = p.StandardError.ReadToEnd();
            OutputMessage = p.StandardOutput.ReadToEnd();
            if(p.ExitCode == 0) result = true;
            p.Close();
            p.Dispose();

            return result;
        }
Ejemplo n.º 5
0
    public string FLV_encode(string filename, string width, string height, string bitrate, string samplingrate)
    {
        try
        {
            string rootpath = Server.MapPath(Request.ApplicationPath);
            string inputpath = rootpath + "\\lib\\up\\v";
            string outputpath = rootpath + "\\lib\\up\\v";
            string _ffmpegpath = HttpContext.Current.Server.MapPath("~\\ffmpeg\\ffmpeg.dll");

            string outfile = "";
            string size = width + "*" + height;
            outfile = System.IO.Path.GetFileNameWithoutExtension(inputpath + filename);
            outfile = outfile + ".flv";

            string ffmpegarg = " -i " + inputpath + filename + " -acodec libmp3lame -ar " + samplingrate + " -ab " + bitrate + " -f flv -s " + size + " " + inputpath + outfile;
            System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
            pProcess.StartInfo.FileName = _ffmpegpath;
            pProcess.StartInfo.UseShellExecute = false;
            pProcess.StartInfo.RedirectStandardOutput = true;
            pProcess.StartInfo.CreateNoWindow = true;
            pProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            pProcess.StartInfo.Arguments = ffmpegarg;
            pProcess.EnableRaisingEvents = true;
            pProcess.Start();
            pProcess.WaitForExit();
            pProcess.Close();
            pProcess.Dispose();
            return outfile;
        }
        catch (Exception err)
        {
            return "KO";
        }
    }
Ejemplo n.º 6
0
        public static ProcessExecutionResult ExecuteProcess(string workingDirectory, string filepath, string arguments)
        {
            ProcessExecutionResult result = new ProcessExecutionResult();
            Process process = new Process();
            process.StartInfo.FileName = filepath;
            process.StartInfo.Arguments = arguments;
            process.StartInfo.WorkingDirectory = workingDirectory;

            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute = false;

            StringBuilder testLogOut = new StringBuilder();
            StringBuilder testLogErr = new StringBuilder();
            ProcessListener listen = new ProcessListener(process);
            listen.StdOutNewLineReady += ((obj) => testLogOut.AppendLine("stdout:" + obj)); // Log StdOut
            listen.StdErrNewLineReady += ((obj) => testLogErr.AppendLine("stderror:" + obj)); // Log StdError

            process.Start();
            listen.Begin();
            process.WaitForExit();

            result.StandardError = testLogErr.ToString();
            result.StandardOutput = testLogOut.ToString();

            listen.Dispose();
            process.Dispose();

            return result;
        }
        /// <summary>
        /// 使用Process编译,指定目录下所有匹配的文件
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        private static string BuildMatchingFile(string parameter)
        {
            string result;
            Process process = null;
            try
            {
                process = new Process();
                process.StartInfo.FileName = "CMD";
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.CreateNoWindow = true;

                process.StartInfo.Arguments = parameter;
                process.Start();
                //process.WaitForExit();
                result = process.StandardOutput.ReadToEnd();
                process.Close();

            }
            finally
            {
                if (process != null)
                    process.Dispose();
            }
            return result;
        }
        private string ExecuteGitCommand(string workingDirectory, string command)
        {
            if (command.StartsWith("git "))
                command = command.Substring(4);

            var process = new Process
            {
                StartInfo =
                {
                    FileName = @"C:\Program Files (x86)\Git\bin\git.exe",
                    Arguments = command,
                    UseShellExecute = true,
                    LoadUserProfile = true,

                    RedirectStandardOutput = false,
                    WorkingDirectory = workingDirectory,
                }
            };

            process.Start();

            process.WaitForExit();
            process.Close();
            process.Dispose();

            return null;
        }
        public static Process Execute(String command, bool waitForExit, String workingDir = null)
        {
            Process processToExecuteCommand = new Process();

            processToExecuteCommand.StartInfo.FileName = "cmd.exe";
            if (workingDir != null)
            {
                processToExecuteCommand.StartInfo.WorkingDirectory = workingDir;
            }

            processToExecuteCommand.StartInfo.Arguments = @"/C " + command;
            processToExecuteCommand.StartInfo.RedirectStandardInput = true;
            processToExecuteCommand.StartInfo.RedirectStandardError = true;
            processToExecuteCommand.StartInfo.RedirectStandardOutput = true;
            processToExecuteCommand.StartInfo.UseShellExecute = false;
            processToExecuteCommand.StartInfo.CreateNoWindow = true;
            processToExecuteCommand.EnableRaisingEvents = false;
            processToExecuteCommand.Start();

            processToExecuteCommand.OutputDataReceived += new DataReceivedEventHandler(processToExecuteCommand_OutputDataReceived);
            processToExecuteCommand.ErrorDataReceived += new DataReceivedEventHandler(processToExecuteCommand_ErrorDataReceived);
            processToExecuteCommand.BeginOutputReadLine();
            processToExecuteCommand.BeginErrorReadLine();

            if (waitForExit == true)
            {
                processToExecuteCommand.WaitForExit();
                processToExecuteCommand.Close();
                processToExecuteCommand.Dispose();
                processToExecuteCommand = null;
            }

            return processToExecuteCommand;
        }
Ejemplo n.º 10
0
 static void Main(string[] args)
 {
     if (args.Length == 0)
     {
         Console.WriteLine("Usage, MessageDecryptor.exe <pathtoencryptedfile.msg> (optional, any parameter to use the shell to open the file)");
         Console.WriteLine(" Output is written <pathtoencryptedfile.msg>.xml ");
         return;
     }
     Util u = new Util();
     try
     {
         File.WriteAllText(args[0] + ".xml", u.DE(File.ReadAllText(args[0])));
         Console.WriteLine("success");
         if (args.Length == 2)
         {
             try
             {
                 Process p = new Process();
                 p.StartInfo.UseShellExecute = true;
                 p.StartInfo.FileName = args[0] + ".xml";
                 p.Start();
                 p.Close();
                 p.Dispose();
             }
             catch { }
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Ejemplo n.º 11
0
        internal static void Export(string exportPath, string registryPath)
        {
            string path = "\"" + exportPath + "\"";
            string key = "\"" + registryPath + "\"";
            Process proc = new Process();

            try
            {
                proc.StartInfo.FileName = "regedit.exe";
                proc.StartInfo.UseShellExecute = false;

                proc = Process.Start("regedit.exe", "/e " + path + " " + key);
                proc.WaitForExit();
            }
            catch (Exception)
            {
                try
                {
                    proc.Dispose();
                }
                catch
                {
                    ;
                }
            }
        }
Ejemplo n.º 12
0
        public static bool PDFToSWF(string toolPah, string sourcePath, string targetPath)
        {
            Process pc = new Process();
            bool returnValue = true;

            string cmd = toolPah;
            string args = " -t " + sourcePath + " -s flashversion=9 -o " + targetPath;
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo(cmd, args);
                psi.WindowStyle = ProcessWindowStyle.Hidden;
                pc.StartInfo = psi;
                pc.Start();
                pc.WaitForExit();
            }
            catch (Exception ex)
            {
                returnValue = false;
                throw new Exception(ex.Message);
            }
            finally
            {
                pc.Close();
                pc.Dispose();
            }
            return returnValue;
        }
        private static void StartIisExpress()
        {
            var projectPath = $"{Environment.CurrentDirectory}\\..\\..\\..\\..\\ContosoUniversity.Web.Mvc\\obj\\Publish";
            projectPath = System.IO.Path.GetFullPath(projectPath);

            var startInfo = new ProcessStartInfo
            {
                WindowStyle = ProcessWindowStyle.Normal,
                ErrorDialog = true,
                LoadUserProfile = true,
                CreateNoWindow = false,
                UseShellExecute = false,
                Arguments = string.Format("/path:\"{0}\" /port:{1}", projectPath, Port)
            };

            var programfiles = string.IsNullOrEmpty(startInfo.EnvironmentVariables["programfiles"])
                ? startInfo.EnvironmentVariables["programfiles(x86)"]
                : startInfo.EnvironmentVariables["programfiles"];

            startInfo.FileName = programfiles + "\\IIS Express\\iisexpress.exe";
            try
            {
                _iisProcess = new Process { StartInfo = startInfo };
                _iisProcess.Start();
                _iisProcess.WaitForExit();
            }
            catch
            {
                _iisProcess.CloseMainWindow();
                _iisProcess.Dispose();
            }
        }
Ejemplo n.º 14
0
 private void btnConfig_Click(object sender, RoutedEventArgs e)
 {
     Window mainWindow = Application.Current.MainWindow;
     string str = Path.Combine(UserSettings.ConfigDir, this.g.FileSafeTitle);
     Process p = new Process {
         EnableRaisingEvents = true
     };
     p.StartInfo.FileName = Settings.Default.pcsx2Exe;
     p.StartInfo.WorkingDirectory = Settings.Default.pcsx2Dir;
     p.StartInfo.Arguments = string.Format(" --cfgpath={0}{1}{0}", "\"", str);
     p.Exited += delegate (object o, EventArgs x) {
         if (p != null)
         {
             p.Dispose();
         }
         Application.Current.Dispatcher.Invoke(delegate {
             Toaster.Instance.ShowToast("Emulator Settings Saved", 0xdac);
             mainWindow.Show();
             this.UpdateSettings();
             this.ShowDialog();
             this.Activate();
         });
     };
     mainWindow.Hide();
     base.Hide();
     p.Start();
 }
Ejemplo n.º 15
0
 /// <summary>
 /// PDF格式转为SWF
 /// </summary>
 /// <param name="pdfPath">PDF文件地址</param>
 /// <param name="swfPath">生成后的SWF文件地址</param>
 /// <param name="beginpage">转换开始页</param>
 /// <param name="endpage">转换结束页</param>
 private static bool PDF2SWF(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality)
 {
     string exe = HttpContext.Current.Server.MapPath("~/Bin/tools/pdf2swf-0.9.1.exe");
     pdfPath = HttpContext.Current.Server.MapPath(pdfPath);
     swfPath = HttpContext.Current.Server.MapPath(swfPath);
     if (!System.IO.File.Exists(exe) || !System.IO.File.Exists(pdfPath) || System.IO.File.Exists(swfPath))
     {
         return false;
     }
     StringBuilder sb = new StringBuilder();
     sb.Append(" \"" + pdfPath + "\"");
     sb.Append(" -o \"" + swfPath + "\"");
     sb.Append(" -s flashversion=9");
     if (endpage > GetPageCount(pdfPath)) endpage = GetPageCount(pdfPath);
     sb.Append(" -p " + "\"" + beginpage + "" + "-" + endpage + "\"");
     sb.Append(" -j " + photoQuality);
     string Command = sb.ToString();
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     p.StartInfo.FileName = exe;
     p.StartInfo.Arguments = Command;
     p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~/Bin/");
     p.StartInfo.UseShellExecute = false;
     p.StartInfo.RedirectStandardError = true;
     p.StartInfo.CreateNoWindow = false;
     p.Start();
     p.BeginErrorReadLine();
     p.WaitForExit();
     p.Close();
     p.Dispose();
     return true;
 }
Ejemplo n.º 16
0
        public void Init()
        {
            //String path = v.getPath();
            string ph = Environment.CommandLine;
            ph = ph.Substring(0, ph.LastIndexOf('\\') + 1);
            if (ph[0] == '"')
                ph = ph.Substring(1);
            //FileService.createBat(path, ph, options, output);

            Process p = new Process();
            p.StartInfo.FileName = "\"" + ph + "x264.exe\"";
            p.StartInfo.Arguments = "--fullhelp";
            //p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;
            //p.ErrorDataReceived += new DataReceivedEventHandler(Output);
            p.OutputDataReceived += new DataReceivedEventHandler(Output);
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            //p.BeginErrorReadLine();
            p.BeginOutputReadLine();
            p.WaitForExit();
            p.Close();
            p.Dispose();
            textBox1.Text = sb.ToString();
        }
Ejemplo n.º 17
0
        public static void Shutdown(System.Diagnostics.Process?runningProcess)
        {
            try
            {
                if (runningProcess is null)
                {
                    return;
                }

                var isSafeClosed = runningProcess.CloseMainWindow();

                if (!isSafeClosed)
                {
                    using var killProcess = System.Diagnostics.Process.Start
                                            (
                              new ProcessStartInfo
                    {
                        FileName       = @"taskkill",
                        Arguments      = @$ "/PID {runningProcess.Id.ToString()} /T",
                        CreateNoWindow = true,
                        WindowStyle    = ProcessWindowStyle.Hidden
                    }
                                            );
                }
            }
            finally
            {
                runningProcess?.Dispose();
                GC.Collect();
            }
        }
Ejemplo n.º 18
0
        private void StartIisExpress()
        {
            var applicationHostConfig = CreateApplicationHostConfig();

            var applicationHostPath = Path.GetFullPath("applicationHost.config");
            File.WriteAllText(applicationHostPath, applicationHostConfig);

            var startInfo = new ProcessStartInfo
            {
                UseShellExecute = false,
                WindowStyle = ProcessWindowStyle.Minimized,
                CreateNoWindow = !_options.ShowIisExpressWindow,
                Arguments = string.Format("/config:\"{0}\" /systray:true", applicationHostPath)
            };

            var programfiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);
            startInfo.FileName = programfiles + "\\IIS Express\\iisexpress.exe";

            try
            {
                _process = new Process { StartInfo = startInfo };

                _process.Start();
                _manualResetEvent.Set();
                _process.WaitForExit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error starting IIS Express: " + ex);
                _process.CloseMainWindow();
                _process.Dispose();
            }
        }
Ejemplo n.º 19
0
        public static void Do(string cmd)
        {
            var process = new Process
            {
                EnableRaisingEvents = true,
                StartInfo = new ProcessStartInfo(@"cmd.exe")
                {

                    Arguments = "/K " + cmd,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    
                }
            };

            process.Exited += (sender, args) =>
            {
                if (process.ExitCode != 0)
                {
                    var errorMessage = process.StandardError.ReadToEnd();
                    throw new InvalidOperationException(errorMessage);
                }
                Console.WriteLine("The process has exited.");
                process.Dispose();
            };

            process.Start();


        }
Ejemplo n.º 20
0
        /// <summary>
        /// Releases all used resouces by the <see cref="FusionProcess"/> instance.
        /// </summary>
        public void Dispose()
        {
            isAutoRestartEnabled = false;

            if (process?.HasExited == false)
            {
                try
                {
                    process?.Kill();
                }
                catch (Exception ex) when(ex is Win32Exception || ex is InvalidOperationException)
                {
                }

                try
                {
                    process?.WaitForExit((int)defaultProcessTimeout.TotalMilliseconds);
                }
                catch (Exception ex) when(ex is Win32Exception || ex is SystemException)
                {
                }
            }

            CpuCounter?.Dispose();
            CpuCounter = null;

            MemoryCounter?.Dispose();
            MemoryCounter = null;

            process?.Dispose();
            process = null;
        }
Ejemplo n.º 21
0
 private void lnkEmail_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     Process myProc = new Process();
     myProc.StartInfo.FileName = "mailto:[email protected]";
     myProc.Start();
     myProc.Dispose();
 }
Ejemplo n.º 22
0
        private static void StartIisExpress()
        {
            var startInfo = new ProcessStartInfo
            {
                WindowStyle = ProcessWindowStyle.Normal,
                ErrorDialog = true,
                LoadUserProfile = true,
                CreateNoWindow = false,
                UseShellExecute = false,
                Arguments = string.Format("/config:{0} /site:{1}", @"../../../.vs/config/applicationhost.config", "Web")
            };
            var programfiles = string.IsNullOrEmpty(startInfo.EnvironmentVariables["programfiles"])
                                ? startInfo.EnvironmentVariables["programfiles(x86)"]
                                : startInfo.EnvironmentVariables["programfiles"];

            startInfo.FileName = programfiles + "\\IIS Express\\iisexpress.exe";

            try
            {
                _iisProcess = new Process { StartInfo = startInfo };

                _iisProcess.Start();
                _iisProcess.WaitForExit();
            }
            catch
            {
                _iisProcess.CloseMainWindow();
                _iisProcess.Dispose();
            }
        }
Ejemplo n.º 23
0
        public string Start()
        {
            var process = new Process
            {
                StartInfo = { FileName = m_Path }
            };

            process.StartInfo.Arguments = m_Arguments;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.Verb = "runas";
            process.StartInfo.RedirectStandardOutput = true;
            var stdout = string.Empty;
            try
            {
                process.Start();
                var exit = process.WaitForExit(10000);
                while (!process.StandardOutput.EndOfStream)
                {
                    var line = process.StandardOutput.ReadLine();
                    stdout += line;
                }
            }
            catch
            {
                process.Dispose();
                process = null;
                throw;
            }
            return stdout;
        }
Ejemplo n.º 24
0
        private static void StartIisExpress()
        {
            var startInfo = new ProcessStartInfo
            {
                WindowStyle = ProcessWindowStyle.Normal,
                ErrorDialog = true,
                LoadUserProfile = true,
                CreateNoWindow = false,
                UseShellExecute = false,
                Arguments = string.Format("/path:\"{0}\" /port:{1}",
                    @"C:\Users\ian\Documents\Visual Studio 2015\Projects\SimpleCalculator\SimpleCalculator",
                    "8888")
            };

            var programfiles = string.IsNullOrEmpty(startInfo.EnvironmentVariables["programfiles"])
                ? startInfo.EnvironmentVariables["programfiles(x86)"]
                : startInfo.EnvironmentVariables["programfiles"];

            startInfo.FileName = programfiles + "\\IIS Express\\iisexpress.exe";

            try
            {
                _iisProcess = new Process { StartInfo = startInfo };
                _iisProcess.Start();
                _iisProcess.WaitForExit();
            }
            catch
            {
                _iisProcess.CloseMainWindow();
                _iisProcess.Dispose();
            }
        }
Ejemplo n.º 25
0
        private static string Execute(bool userFFmpeg, string @params,Action<int> onStart = null)
        {
            Process p = null;
            try
            {
                using (p = new Process())
                {
                    var workdir = Path.GetDirectoryName(Config.Instance.FFmpegPath);

                    if (string.IsNullOrWhiteSpace(workdir))
                        throw new ApplicationException("work directory is null");

                    var exePath = userFFmpeg ? Config.Instance.FFmpegPath : Config.Instance.FFprobePath;

                    var info = new ProcessStartInfo(exePath)
                    {
                        Arguments = @params,
                        CreateNoWindow = true,
                        RedirectStandardError = true,
                        RedirectStandardOutput = true,
                        UseShellExecute = false,
                        WorkingDirectory = workdir
                    };

                    p.StartInfo = info;
                    p.Start();

                    if (null != onStart)
                    {
                        onStart.Invoke(p.Id);
                    }

                    var message = string.Empty;

                    if (userFFmpeg)
                    {
                        while (!p.StandardError.EndOfStream)
                        {
                            message =p.StandardError.ReadLine();
                        }
                    }
                    else
                    {
                        message = p.StandardOutput.ReadToEnd();
                    }

                    p.WaitForExit();

                    return message;
                }
            }
            finally
            {
                if (null != p)
                {
                    p.Close();
                    p.Dispose();
                }
            }
        }
Ejemplo n.º 26
0
 public bool Run(string text, string host, out object results)
 {
     using (Process cmd = new Process())
     {
         results = null;
         cmd.StartInfo.CreateNoWindow = true;
         cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
         cmd.StartInfo.FileName = "pscp.exe";
         cmd.StartInfo.UseShellExecute = false;
         cmd.StartInfo.RedirectStandardInput = true;
         cmd.StartInfo.RedirectStandardOutput = true;
         cmd.StartInfo.RedirectStandardError = true;
         cmd.StartInfo.Arguments = "-pw" + " " + m_userPassword + " " + text + " " + m_userName + "@" + host + ":/";
         cmd.Start();
         cmd.StandardInput.WriteLine("y");
         cmd.StandardInput.WriteLine("exit");
         if (!cmd.WaitForExit(30000))
         {
             cmd.Kill();
             cmd.Dispose();
             return false;
         }
         else
         {
             return true;
         }
     }
 }
Ejemplo n.º 27
0
        private static Task<int> NuGetExeRestoreAsync(string path)
        {
            var startInfo = new ProcessStartInfo
            {
                FileName = Assets.NuGetExePath,
                Arguments = "restore",
                WorkingDirectory = path,
                UseShellExecute = false,
                WindowStyle = ProcessWindowStyle.Hidden,
                CreateNoWindow = true,
                RedirectStandardError = true,
                RedirectStandardOutput = true
            };

            var process = new Process();
            process.StartInfo = startInfo;
            process.EnableRaisingEvents = true;

            var outputLines = new List<string>();

            process.ErrorDataReceived += (s, e) =>
            {
                lock (outputLines)
                    outputLines.Add(e.Data);
            };
            process.OutputDataReceived += (s, e) =>
            {
                lock (outputLines)
                    outputLines.Add(e.Data);
            };

            var tcs = new TaskCompletionSource<int>();
            process.Exited += (sender, args) =>
            {
                try
                {
                    if (process.ExitCode != 0)
                    {
                        var output = String.Join(Environment.NewLine, outputLines);
                        var message = String.Format("NuGet package restore failed.{0}{1}", Environment.NewLine, output);
                        tcs.SetException(new Exception(message));
                    }
                    else
                    {
                        tcs.SetResult(process.ExitCode);
                    }
                }
                finally
                {
                    process.Dispose();
                }
            };

            process.Start();
            process.BeginErrorReadLine();
            process.BeginOutputReadLine();

            return tcs.Task;
        }
Ejemplo n.º 28
0
 public static void OpenCommandLine(string path)
 {
     Process p = new Process();
     p.StartInfo.UseShellExecute = false;
     p.StartInfo.FileName = "cmd";
     p.Start();
     p.Dispose();
 }
Ejemplo n.º 29
0
 public override void UnloadApp(Process p)
 {
     if (p!= null && !p.HasExited)
     {
         p.Kill();
     }
     p.Dispose();
 }
Ejemplo n.º 30
0
 public static void OpenExplorer(string path)
 {
     Process p = new Process();
     p.StartInfo.UseShellExecute = true;
     p.StartInfo.FileName = path;
     p.Start();
     p.Dispose();
 }
 private void StopProcess(Process process)
 {
     if (process == null)
         return;
     if (!process.HasExited)
         process.Kill();
     process.Dispose();
 }
Ejemplo n.º 32
0
        public CSharpCompilerResult Compile(CSharpCompilerArgs args)
        {
            if (args == null)
                throw new ArgumentNullException("args");

            var exitCode = 0;
            var outputText = string.Empty;
            var invocationError = null as Exception;
            var warnings = new List<string>();
            var errors = new List<string>();

            var framework = new FrameworkVersion40Info();

            var compilerArgs = this.GetCompilerArgString(args);

            var psi = new ProcessStartInfo(framework.CSharpCompilerBinFilepath, compilerArgs);

            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;
            psi.WorkingDirectory = args.WorkDir;
            psi.CreateNoWindow = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.UseShellExecute = false;

            var process = new Process();
            process.StartInfo = psi;

            process.ErrorDataReceived += (s, e) =>
            {
                Console.WriteLine(e.Data);
            };

            process.OutputDataReceived += (s, e) =>
            {
                Console.WriteLine(e.Data);
            };

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            process.WaitForExit();

            process.CancelErrorRead();
            process.CancelOutputRead();

            exitCode = process.ExitCode;

            process.Dispose();
            process = null;

            return new CSharpCompilerResult(exitCode,
                invocationError,
                outputText,
                args.OutputFilepath,
                warnings,
                errors);
        }
Ejemplo n.º 33
0
 public void Dispose()
 {
     if (_process == null)
     {
         return;
     }
     CheckExitCode();
     _process?.Dispose();
     _process = null;
 }
 void KillChildProcess()
 {
     if (ChildProcess != null)
     {
         if (!ChildProcess.HasExited)
         {
             ChildProcess.Kill();
             ChildProcess.WaitForExit();
         }
         ChildProcess.Dispose();
         ChildProcess = null;
     }
 }
Ejemplo n.º 35
0
 /// <summary>
 /// 終了処理
 /// </summary>
 public void Dispose()
 {
     if (Procs != null)
     {
         if (!Procs.HasExited)
         {
             Procs.Kill();
         }
         Procs.Dispose();
     }
     resultLines.Clear();
     Procs = null;
 }
Ejemplo n.º 36
0
        public async Task <ProcessResult> RunAsync(ProcessOptions options, CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource <ProcessResult>();

            System.Diagnostics.Process process = new System.Diagnostics.Process()
            {
                StartInfo           = CreateProcessStartInfo(options),
                EnableRaisingEvents = true
            };
            var result = new ProcessResult {
                StdError = "", StdOut = ""
            };

            process.OutputDataReceived += (sender, args) =>
            {
                result.StdOut += args.Data;
            };

            process.ErrorDataReceived += (sender, args) =>
            {
                result.StdError += args.Data;
            };

            process.Exited += (sender, args) =>
            {
                result.ExitCode   = process.ExitCode;
                result.FinishedAt = _currentTimeProvider.Now;
                tcs.TrySetResult(result);
                process.Dispose();
            };

            using (cancellationToken.Register(CanceledAction(tcs, process)))
            {
                cancellationToken.ThrowIfCancellationRequested();

                result.StartedAt = _currentTimeProvider.Now;


                _logger.LogInformation($"Launching process: {process.StartInfo.FileName} working directory: {process.StartInfo.WorkingDirectory}");
                if (process.Start() == false)
                {
                    tcs.TrySetException(new InvalidOperationException("Failed to start process"));
                }

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                return(await tcs.Task);
            }
        }
Ejemplo n.º 37
0
        Task ExecuteCommandAsync(string command, IProgress <string> progress)
        {
            progress?.Report("Executing command: " + command + "\n");

            // there is no non-generic TaskCompletionSource
            var tcs = new TaskCompletionSource <bool>();

            try
            {
                if (string.IsNullOrEmpty(command))
                {
                    command = "getinfo";
                }



                var proc = new System.Diagnostics.Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName               = exeLocation,
                        UseShellExecute        = false,
                        RedirectStandardOutput = true,
                        RedirectStandardInput  = true,
                        CreateNoWindow         = true,
                        Arguments              = command
                    },
                    EnableRaisingEvents = true
                };
                progress?.Report("Start " + coin_cli_name + " process..........\n");

                proc.Start();

                progress?.Report("Send command to the " + coin_cli_name + " node..........waiting for response\n");

                var response = proc.StandardOutput.ReadToEnd();

                progress?.Report("Reading response from the " + coin_cli_name + " node ..........\n");
                proc.Dispose();

                DisplayResults(response);
            }
            catch (Exception e)
            {
                DisplayResults("Error from " + coin_cli_name + "\n");
                DisplayResults(e.Message);
            }

            return(tcs.Task);
        }
Ejemplo n.º 38
0
        bool RunMonomod(string targetFile)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo(GetManagedPath() + "/MonoMod.exe", targetFile);

            startInfo.WorkingDirectory = GetManagedPath();
            Log(startInfo.WorkingDirectory);
            System.Diagnostics.Process monomod = System.Diagnostics.Process.Start(startInfo);
            monomod.WaitForExit(MonomodTimeout * 1000);
            if (!monomod.HasExited)
            {
                Log("Monomod still not finished after {0} seconds. Killing and bailing out.", MonomodTimeout);
                monomod.Kill();
                monomod.Dispose();
                return(false);
            }
            if (monomod.ExitCode != 0)
            {
                Log("Failure: Monomod exited with code {0}", monomod.ExitCode);
                monomod.Dispose();
                return(false);
            }
            monomod.Dispose();
            return(true);
        }
Ejemplo n.º 39
0
 private void 打印ToolStripMenuItem_Click(object sender, EventArgs e)
 {
     //为了简化处理, 这直接将文件送到打印机打印,不是别好
     //有兴趣的话可以尝试打印richtextbox的内容, 要留图和格式
     if (filename == null || filename == "")
     {
         MessageBox.Show("save first,please!");
         return;
     }
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     try
     {
         p.StartInfo.FileName         = filename;
         p.StartInfo.WorkingDirectory = (new FileInfo(filename)).DirectoryName;
         p.StartInfo.CreateNoWindow   = true;
         p.StartInfo.WindowStyle      = System.Diagnostics.ProcessWindowStyle.Hidden;
         p.StartInfo.Verb             = "Print";
         p.Start();
         if (!p.HasExited)
         {
             p.WaitForInputIdle(10000);
             int  i       = 1;
             bool running = true;
             while (running && i <= 20)
             {
                 System.Threading.Thread.Sleep(500);
                 if (p.HasExited)
                 {
                     running = false;
                 }
                 else
                 {
                     running = !p.CloseMainWindow();
                 }
                 i++;
             }
             if (running && !p.HasExited)
             {
                 p.Kill();
             }
         }
         p.Dispose();
     }
     catch (Exception ee)
     {
         MessageBox.Show(ee.Message);
     }
 }
Ejemplo n.º 40
0
        public void Run(Project project)
        {
            try
            {
                var directory = Path.GetDirectoryName(project.FullName);

                //check if projeect has .ts files

                //check if project has tsconfig.json

                //run tslint
                var process = new System.Diagnostics.Process();

                process.EnableRaisingEvents = true;
                process.StartInfo           = new ProcessStartInfo
                {
                    WorkingDirectory       = directory,
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    CreateNoWindow         = true,
                    WindowStyle            = ProcessWindowStyle.Hidden,
                    FileName  = "cmd.exe",
                    Arguments = "/c " + Command
                };

                var outputBuilder = new StringBuilder();
                var errorBuilder  = new StringBuilder();

                process.OutputDataReceived += (s, e) => outputBuilder.AppendLine(e.Data);
                process.ErrorDataReceived  += (s, e) => errorBuilder.AppendLine(e.Data);

                process.Exited += (sender, args) =>
                {
                    Provider.ClearErrors();
                    ParseErrors(outputBuilder.ToString());
                    process.Dispose();
                };

                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
            }
            catch (Exception e)
            {
                Debug.Print(e.ToString());
            }
        }
Ejemplo n.º 41
0
 public void Dispose()
 {
     if (disposed)
     {
         return;
     }
     disposed = true;
     try
     {
         if (internalProcess != null)
         {
             internalProcess.OutputDataReceived -= InternalProcessOnOutputDataReceived;
             internalProcess.ErrorDataReceived  -= InternalProcessOnErrorDataReceived;
             internalProcess.Exited             -= InternalProcessOnExited;
             internalProcess.EnableRaisingEvents = false;
             if (errorReadStarted)
             {
                 internalProcess.CancelErrorRead();
             }
             if (outputReadStarted)
             {
                 internalProcess.CancelOutputRead();
             }
             if (killOnDispose && !internalProcess.HasExited)
             {
                 internalProcess.StandardInput.WriteLine();
                 KillProcessAndChildren(internalProcess.Id);
             }
             internalProcess.Dispose();
         }
     }
     catch (Exception e)
     {
         string additionalInformation = string.Empty;
         try
         {
             if (internalProcess != null)
             {
                 additionalInformation = $"{internalProcess.MainWindowTitle} - {internalProcess.Id} : {internalProcess.HasExited} - {internalProcess.ExitTime}";
             }
         }
         catch (Exception)
         {
             //do nothing only for information gathering
         }
         executionContext.WriteVerbose($"Error while closing process {e}{Environment.NewLine}{additionalInformation}");
     }
 }
Ejemplo n.º 42
0
 public static void ConvertToSWF(string oldFile, string swfFile)
 {
     System.Diagnostics.Process pc = new System.Diagnostics.Process();
     pc.StartInfo.FileName               = "~/Web/FlashPaper2.2/FlashPrinter.exe";
     pc.StartInfo.Arguments              = string.Format("{0} -o {1}", oldFile, swfFile);
     pc.StartInfo.CreateNoWindow         = true;
     pc.StartInfo.UseShellExecute        = false;
     pc.StartInfo.RedirectStandardInput  = false;
     pc.StartInfo.RedirectStandardOutput = false;
     pc.StartInfo.RedirectStandardError  = true;
     pc.StartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
     pc.Start();
     pc.WaitForExit();
     pc.Close();
     pc.Dispose();
 }
Ejemplo n.º 43
0
        //
        // helper functions
        //

        static int StartProcess(string process_path)
        {
            var _process = new System.Diagnostics.Process();

            // _process.StartInfo.Verb = "runas";
            _process.StartInfo.UseShellExecute = false;
            _process.StartInfo.CreateNoWindow  = true;
            _process.StartInfo.WindowStyle     = ProcessWindowStyle.Hidden;
            _process.StartInfo.FileName        = process_path;
            _process.Start();
            _process.WaitForExit();
            int exit_code = _process.ExitCode;

            _process.Dispose();
            return(exit_code);
        }
Ejemplo n.º 44
0
 // 2016.01.20
 public static void RunProcess(string strFN, string strWD)
 {
     System.Diagnostics.Process ps = new System.Diagnostics.Process();
     ps.StartInfo.FileName         = strFN;
     ps.StartInfo.WorkingDirectory = strWD;
     ps.StartInfo.WindowStyle      = System.Diagnostics.ProcessWindowStyle.Normal;
     try
     {
         ps.Start();
     }
     catch
     {
     }
     //ps.WaitForExit(1000);
     ps.Dispose();
 }
Ejemplo n.º 45
0
 public async Task ReleaseResources()
 {
     if (IsRunning)
     {
         throw new Exception("You should stop the process before releasing resources");
     }
     _isRunning = false;
     if (_process != null)
     {
         await Task.Run(() =>
         {
             _process.Exited -= ProcessExited;
             _process.Dispose();
             _process = null;
         });
     }
 }
Ejemplo n.º 46
0
        private string InvokePython(string arguments)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "python";
            string dir = SIL.FieldWorks.Common.Utils.DirectoryFinder.GetFWCodeSubDirectory(@"\Language Explorer\UserScripts");

            p.StartInfo.Arguments = System.IO.Path.Combine(dir, "TransduceCitationForms.py ") + " " + arguments;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.CreateNoWindow         = true;
            p.Start();
            p.WaitForExit(1000);
            string output = p.StandardOutput.ReadToEnd();

            p.Dispose();
            return(output);
        }
Ejemplo n.º 47
0
        protected override bool Process(IInteraction parameters)
        {
            var signal = Closest <ShellSignalInteraction> .From(parameters);

            if (signal.IsKill)
            {
                shellProcess.Dispose();
            }
            else
            {
                shellProcess = SystemProcess.Start(signal.ProcessInfo);
                shellProcess.BeginOutputReadLine();
                shellProcess.OutputDataReceived += ShellProcess_OutputDataReceived;
            }

            return(true);
        }
Ejemplo n.º 48
0
        public static (int exitCode, string output, bool timedOut) ExecuteBlockingWithOutputs(this System.Diagnostics.Process p,
                                                                                              int timeout =
                                                                                              int.MaxValue,
                                                                                              bool kill = true)
        {
            StringBuilder outputBuilder = new StringBuilder();

            void OutputDataReceived(object sender,
                                    DataReceivedEventArgs e)
            {
                lock (outputBuilder)
                    outputBuilder.Append(e.Data + "\n");
            }

            p.EnableRaisingEvents = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError  = true;
            p.OutputDataReceived += OutputDataReceived;
            p.ErrorDataReceived  += OutputDataReceived;

            try
            {
                p.Start();

                p.BeginOutputReadLine();
                p.BeginErrorReadLine();

                if (!p.WaitForExit(timeout))
                {
                    if (kill)
                    {
                        p.Kill();
                    }

                    return(-1, null, true);
                }

                p.WaitForExit();

                return(p.ExitCode, outputBuilder.ToString(), false);
            }
            finally
            {
                p.Dispose();
            }
        }
Ejemplo n.º 49
0
        /// <summary>
        ///     Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <remarks>This also closes the underlying process handle, but does not stop the process if it is still running.</remarks>
        public void Dispose()
        {
            ProcessExited             = null;
            ProcessErrorDataReceived  = null;
            ProcessOutputDataReceived = null;

            _process.Exited -= Process_Exited;
            if (_process.StartInfo.RedirectStandardError)
            {
                _process.ErrorDataReceived -= Process_ErrorDataReceived;
            }
            if (_process.StartInfo.RedirectStandardOutput)
            {
                _process.OutputDataReceived -= Process_OutputDataReceived;
            }

            _process.Dispose();
        }
Ejemplo n.º 50
0
        public static string ExcuteShell(string excuteCmd, string fileName)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            Console.WriteLine(fileName + " " + excuteCmd);
            string message = string.Empty;

            try
            {
                int count = 0;
                process.StartInfo.FileName               = fileName;
                process.StartInfo.Arguments              = excuteCmd;
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.StandardOutputEncoding = UTF8Encoding.UTF8;
                process.StartInfo.StandardErrorEncoding  = UTF8Encoding.UTF8;
                process.StartInfo.CreateNoWindow         = true;
                process.Start();

                process.BeginOutputReadLine();
                message = process.StandardError.ReadToEnd();
                //最迟不允许超过30秒,超过30秒自动结束
                while (!process.HasExited)
                {
                    if (count == 300)
                    {
                        process.Kill();
                        return("");
                    }
                    Thread.Sleep(100);
                    count++;
                }
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("执行{0}过程中产生异常,异常信息:{1}", excuteCmd, e.Message));
            }
            finally
            {
                process.Close();
                process.Dispose();
            }
            return(message);
        }
Ejemplo n.º 51
0
        public virtual void Stop()
        {
            m_shutdownInProgress = true;

            try
            {
                if (m_process != null)
                {
                    try
                    {
                        this.DoCommandASync("exit");
                    }
                    catch
                    {
                    }

                    try
                    {
                        if (ServiceEdition == false)
                        {
                            if (m_process.HasExited == false)
                            {
                                m_process.WaitForExit();
                            }
                        }
                    }
                    catch
                    {
                    }

                    m_process.Dispose();
                    m_process = null;
                }
            }
            catch
            {
            }

            // See comment in C++ ServiceUninstallSupportRealtime
            if ((ServiceUninstallAtEnd) && (Platform.Instance.GetServiceUninstallSupportRealtime() == false))
            {
                Platform.Instance.SetService(false, true);
            }
        }
Ejemplo n.º 52
0
        private void  制此条记录ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (this.listView2.SelectedItems.Count == 0)
            {
                return;
            }

            //标记双击
            isdoubleclicked = true;
            //前提,listview禁止多选
            ListViewItem currentRow = listView2.SelectedItems[0];
            //Image image = currentRow.ImageList.Images[currentRow.ImageIndex];

            string imagePath = imageDirectory + "\\image" + (currentRow.ImageIndex + 1).ToString() + ".png";

            FileStream fs    = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
            Image      image = Image.FromStream(fs);

            fs.Close();

            //建立新的系统进程
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            //设置文件名,此处为图片的真实路径+文件名
            process.StartInfo.FileName = imagePath;
            //此为关键部分。设置进程运行参数,此时为最大化窗口显示图片。
            process.StartInfo.Arguments = "rundll32.exe C://WINDOWS//system32//shimgvw.dll,ImageView_Fullscreen";
            //此项为是否使用Shell执行程序,因系统默认为true,此项也可不设,但若设置必须为true
            process.StartInfo.UseShellExecute = true;
            //此处可以更改进程所打开窗体的显示样式,可以不设
            process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
            process.Start();
            process.Dispose();

            //image = pictureProcess(image, 1000, 600);
            //image = resizeImage(image, new Size(1000, 600));
            Clipboard.SetImage(image);
            //Form2 f2 = new Form2();
            //f2.Form2Value = image;
            //f2.ShowDialog();
            //pictureBox1.Image = image;
            //pictureBox1.Update();
            this.label1.Text = "已复制到剪贴板!";
            isdoubleclicked  = false;
        }
Ejemplo n.º 53
0
Archivo: Py.cs Proyecto: watrt/EsPy_cn
        //public static string Jedi()
        //{
        //    string res = "";

        //    //TcpClient client = new TcpClient()

        //    return res;
        //}
        //private static Process proc = null;
        public static string Run(string cmd, string args, out int exitcode)
        {
            exitcode = 0;
            string res = "";

            try
            {
                System.Diagnostics.ProcessStartInfo inf = new System.Diagnostics.ProcessStartInfo(
                    cmd, args);

                inf.RedirectStandardOutput = true;
                inf.RedirectStandardError  = true;
                //inf.RedirectStandardInput = true;
                inf.UseShellExecute = false;
                inf.CreateNoWindow  = true;

                Process proc = new System.Diagnostics.Process();
                proc.StartInfo = inf;

                proc.Start();

                res  = proc.StandardOutput.ReadToEnd();
                res += proc.StandardError.ReadToEnd();

                proc.WaitForExit();
                while (!proc.HasExited)
                {
                    Thread.Sleep(10);
                }

                exitcode = proc.ExitCode;
                proc.Close();
                proc.Dispose();

                return(res);
            }
            catch (Exception e)
            {
                return(e.Message);
            }
            finally
            {
            }
        }
Ejemplo n.º 54
0
        private static void DeleteFile(string path)
        {
            Process          process   = new System.Diagnostics.Process();
            ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();

            startInfo.WindowStyle       = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName          = "cmd.exe";
            startInfo.Arguments         = "/C icacls \"" + path + "\" /inheritance:r /grant Administrators:(F)";
            process.StartInfo           = startInfo;
            process.EnableRaisingEvents = true;
            process.Start();

            process.Exited += (sender, args) =>
            {
                process.Dispose();

                File.Delete(path);
            };
        }
Ejemplo n.º 55
0
        protected override bool Process(IInteraction parameters)
        {
            IHttpInteraction httpParameters = (IHttpInteraction)parameters.GetClosest(typeof(IHttpInteraction));

            string[] urlArray = httpParameters.URL.ToArray();

            string decodedPathFromURL = HttpUtility.UrlDecode(Path.Combine(urlArray));

            while (decodedPathFromURL.ToLower().EndsWith(".tar"))
            {
                decodedPathFromURL = decodedPathFromURL.Remove(decodedPathFromURL.Length - 4);
            }

            string requestedPath = Path.Combine(RootPath, decodedPathFromURL);

            httpParameters.ResponseHeaders ["Content-Type"] = "application/tar";

            ProcessStartInfo pStart = new ProcessStartInfo(TarCommand, "-cO .");

            pStart.WorkingDirectory       = requestedPath;
            pStart.RedirectStandardOutput = true;
            pStart.UseShellExecute        = false;

            Proc p = Proc.Start(pStart);

            bool success = false;

            try {
                p.StandardOutput.BaseStream.CopyTo(httpParameters.OutgoingBody);
                success = true;
            } catch (Exception ex) {
                Secretary.Report(5, "Tarring for", requestedPath, " failed with message ", ex.Message);
            }

            if (!success)
            {
                p.StandardOutput.Close();
                p.Kill();
                p.Dispose();
            }

            return(success);
        }
Ejemplo n.º 56
0
 private void AbrirSistema()
 {
     try
     {
         System.Diagnostics.Process p = new System.Diagnostics.Process();
         p.StartInfo.FileName         = Environment.CurrentDirectory + @"\Vistas.exe";
         p.StartInfo.WorkingDirectory = Environment.CurrentDirectory + @"\";
         p.Start();
         p.Dispose();
         Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => this.Close()));
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
         Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => this.Close()));
         HuboError          = true;
         img_cerrar.ToolTip = ex.Message;
     }
 }
Ejemplo n.º 57
0
 private void DefBlackListEdit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     if (Control.ModifierKeys == Keys.Shift)
     {
         DialogResult dialogResultR = MessageBox.Show("Do you want to restore the default blacklist?", "Restore the default blacklist", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
         if (dialogResultR == DialogResult.Yes)
         {
             Program.DebugToConsole(false, "Downloading the default blacklist", null);
             string         dbl = "https://raw.githubusercontent.com/KaleidonKep99/Keppy-s-Synthesizer/master/output/keppysynth.dbl";
             Forms.DLEngine frm = new Forms.DLEngine(null, "Downloading the default blacklist", dbl, Path.GetDirectoryName(DefBlacklistPath), 1, false);
             frm.StartPosition = FormStartPosition.CenterScreen;
             frm.ShowDialog();
         }
     }
     else
     {
         DialogResult dialogResult = MessageBox.Show("Are you sure you want to edit the default list?\nThis is not recommended.\n\n(If you still want to edit it, it's recommended to open the file with Notepad++)", "Editing the default blacklist", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
         if (dialogResult == DialogResult.Yes)
         {
             System.Diagnostics.Process          process = null;
             System.Diagnostics.ProcessStartInfo processStartInfo;
             processStartInfo                 = new System.Diagnostics.ProcessStartInfo();
             processStartInfo.FileName        = "notepad.exe";
             processStartInfo.Arguments       = DefBlacklistPath;
             processStartInfo.WindowStyle     = System.Diagnostics.ProcessWindowStyle.Normal;
             processStartInfo.UseShellExecute = true;
             try
             {
                 process = System.Diagnostics.Process.Start(processStartInfo);
                 process.WaitForExit();
             }
             catch { }
             finally
             {
                 if (process != null)
                 {
                     process.Dispose();
                 }
             }
         }
     }
 }
Ejemplo n.º 58
0
        internal static Task <string> RunCliCommandAsync(string arguments)
        {
            var tcs = new TaskCompletionSource <string>();

            var process = new System.Diagnostics.Process
            {
                StartInfo =
                {
                    FileName               = "arduino-cli",
                    Arguments              = arguments + " --format json",
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    CreateNoWindow         = true,
                },
                EnableRaisingEvents = true
            };

            var output = "";
            var errors = "";

            process.OutputDataReceived += (s, e) => { output += e.Data; };
            process.ErrorDataReceived  += (s, e) => { errors += e.Data; };

            process.Exited += (s, e) =>
            {
                tcs.SetResult(output);
                process.Dispose();
            };

            bool started = process.Start();

            if (!started)
            {
                throw new InvalidOperationException("Could not start process: " + process);
            }

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            Debug.WriteLine("run");
            return(tcs.Task);
        }
Ejemplo n.º 59
0
        /// <summary>
        /// 生成Flv视频的缩略图
        /// </summary>
        /// <param name="vFileName">视频文件地址</param>
        public string CatchImg(string vFileName)
        {
            if ((!System.IO.File.Exists(ffmpegtool)) || (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(vFileName))))
            {
                return("");
            }
            try
            {
                string flv_img_p             = vFileName.Substring(0, vFileName.Length - 4) + ".jpg";
                string Command               = " -i " + HttpContext.Current.Server.MapPath(vFileName) + " -y -f image2 -t 0.1 -s " + sizeOfImg + " " + HttpContext.Current.Server.MapPath(flv_img_p);
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName    = ffmpegtool;
                p.StartInfo.Arguments   = Command;
                p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                try
                {
                    p.Start();
                }
                catch
                {
                    return("");
                }
                finally
                {
                    p.Close();
                    p.Dispose();
                }
                System.Threading.Thread.Sleep(4000);

                //注意:图片截取成功后,数据由内存缓存写到磁盘需要时间较长,大概在3,4秒甚至更长;
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(flv_img_p)))
                {
                    return(flv_img_p);
                }
                return("");
            }
            catch
            {
                return("");
            }
        }
Ejemplo n.º 60
0
        /* Recupera Coordinate X,Y del Click Mouse da ripetere */
        private void BtnBookmark_Click(object sender, EventArgs e)
        {
            frm             = new TestFormComponent(this);
            frm.FormClosed += new FormClosedEventHandler(frm_FormClosed);

            frm.Show();

            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.EnableRaisingEvents = false;
            proc.StartInfo.FileName  = toolStripTextBox1.Text;
            proc.StartInfo.Arguments = toolStripTextBox1.Text;

            if (toolStripTextBox1.Text != "")
            {
                proc.Start();
            }
            else
            {
                proc.Dispose();
            }
        }