Search Results

Search found 97 results on 4 pages for 'processstartinfo'.

Page 3/4 | < Previous Page | 1 2 3 4  | Next Page >

  • Is SQLDataReader slower than using the command line utility sqlcmd?

    - by Andrew
    I was recently advocating to a colleague that we replace some C# code that uses the sqlcmd command line utility with a SqlDataReader. The old code uses: System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + sqlCmd); wher sqlCmd is something like "sqlcmd -S " + serverName + " -y 0 -h-1 -Q " + "\"" + "USE [" + database + "]" + ";+ txtQuery.Text +"\"";\ The results are then parsed using regular expressions. I argued that using a SQLDataReader woud be more in line with industry practices, easier to debug and maintain and probably faster. However, the SQLDataReader approach is at least the same speed and quite possibly slower. I believe I'm doing everything correctly with SQLDataReader. The code is: using (SqlConnection connection = new SqlConnection()) { try { SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString); connection.ConnectionString = builder.ToString(); ; SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); // do stuff w/ reader reader.Close(); } catch (Exception ex) { outputMessage += (ex.Message); } } I've used System.Diagnostics.Stopwatch to time both approaches and the command line utility (called from C# code) does seem faster (20-40%?). The SqlDataReader has the neat feature that when the same code is called again, it's lightening fast, but for this application we don't anticipate that. I have already done some research on this problem. I note that the command line utility sqlcmd uses OLE DB technology to hit the database. Is that faster than ADO.NET? I'm really suprised, especially since the command line utility approach involves starting up a process. I really thought it would be slower. Any thoughts? Thanks, Dave

    Read the article

  • Read StandardOutput Process from BackgroundWorkerProcess method

    - by Nicola Celiento
    Hi all, I'm working with a BackgroundWorker Process from Windows .NET C# application. From the async method I call many instance of cmd.exe Process (foreach), and read from StandardOutput, but at the 3-times cycle the ReadToEnd() method throw Timeout Exception. Here the code: StreamWriter sw = null; DataTable dt2 = null; StringBuilder result = null; Process p = null; for(DataRow dr in dt1.Rows) { arrLine = new string[4]; //new row result = new StringBuilder(); arrLine[0] = dr["ID"].ToString(); arrLine[1] = dr["ChangeSet"].ToString(); #region Initialize Process CMD p = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "cmd.exe"; info.CreateNoWindow = true; info.RedirectStandardInput = true; info.RedirectStandardOutput = true; info.RedirectStandardError = true; info.UseShellExecute = false; p.StartInfo = info; p.Start(); sw = new StreamWriter(p.StandardInput.BaseStream); #endregion using (sw) { if (sw.BaseStream.CanWrite) { sw.WriteLine("cd " + this.path_WORKDIR); sw.WriteLine("tfpt getcs /changeset:" + arrLine[1]); } } string strError = p.StandardError.ReadToEnd(); // Read shell error output commmand (TIMEOUT) result.Append(p.StandardOutput.ReadToEnd()); // Read shell output commmand sw.Close(); sw.Dispose(); p.Close(); p.Dispose(); } Timeout is on code line: string strError = p.StandardError.ReadToEnd(); Can you help me? Thanks!

    Read the article

  • Java and .net interoperability

    - by dineshrekula
    I have a c# program through which i am opening cmd window as a a process. in this command window i am running a batch file. i am redirecting the output of that batch file commands to a Text File. When i run my application everything seems to be ok. But few times, Application is giving some error like "Can't access the file. it's being used by another application" at the same time cmd window is not getting closed. If we close the cmd process through the Task Manager, then it's writing the content to the file and getting closed. Even though i closed the cmd process, still file handle is not getting released. so that i am not able to run the application next time onwards.Always it's saying Can't access the file. Only after restarting the system, it's working. Here is my code: Process objProcess = new Process(); ProcessStartInfo objProInfo = new ProcessStartInfo(); objProInfo.WindowStyle = ProcessWindowStyle.Maximized; objProInfo.UseShellExecute = true; objProInfo.FileName = "Batch file path" objProInfo.Arguments = "Some Arguments"; if (Directory.Exists(strOutputPath) == false) { Directory.CreateDirectory(strOutputPath); } objProInfo.CreateNoWindow = false; objProcess.StartInfo = objProInfo; objProcess.Start(); objProcess.WaitForExit(); test.bat: java classname argument > output.txt Here is my question: I am not able to trace where the problem is.. How we can see the process which holding handle on ant file. Is there any suggestions for Java and .net interoperability

    Read the article

  • Console app showing message box on error

    - by holz
    I am trying to integrate with a vendors app by calling it with command args from c#. It is meant to automate a process that we need to do with out needing anyone to interact with the application. If there are no errors when running the process it works fine. However if there are any errors the vendors application will show a message box with the error code and error message and wait for someone to click the ok button. When the ok button is clicked it will exit the application returning the error code as the exit code. As my application is going to be a windows service on a server, needing someone to click an okay button will be an issue. Just wondering what the best solution would be to get around this. My code calling the vendor app is... ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "someapp.exe" startInfo.Arguments = "somefile.txt"; Process jobProcess = Process.Start(startInfo); jobProcess.WaitForExit(); int exitCode = jobProcess.ExitCode;

    Read the article

  • how avoids deadlock condition

    - by rima
    Hi I try to write a program like a compiler.In this case I must simulate these codes of SQLPL(This one can be just for example).for example in command prompt i wana do these: c:\> sqlplus .... Enter User-Name:(here we must enter username) xxxx Enter password:(same up)yyyyy ... sql>(now i want to send my sql command to shell)prompt "rima"; "rima" [<-output] sql> prompt "xxxx" sql> exit very simple. I try to use this code: ProcessStartInfo psi = new ProcessStartInfo( @"sqlplus"); psi.UseShellExecute = false; psi.CreateNoWindow = true; psi.RedirectStandardInput = true; psi.RedirectStandardOutput = true; //psi.RedirectStandardError = true; Process process = new Process(); process.StartInfo = psi; bool started = process.Start(); if (started) { process.StandardInput.WriteLine("user/password"); process.StandardInput.Flush(); string ret = process.StandardOutput.ReadLine(); // <-- stalls here System.Console.WriteLine("sqlplus says :" + ret + "\"."); } i find out it form here but as if u read this code has problem!DEADLOCK Condition problem! this is my second time i ask my question,every time my knowledge growing,but i cant get how I can solve my problem at last!!! So I kindly kiss your hand,please help me,these process is not clear for me.any one can give me a code that handle my problem?Already i look at all codes,also I try to use ProcessRunner that in my last post some one offer me,but I cant use it also,i receive an error. I hope by first example u find out what i want,and solve the second code problem... thanks I use C# for implemantation

    Read the article

  • Problem, executing commands in cmd using c#

    - by srk
    I need to execute the below command in command prompt. C:\MySQL\MySQL Server 5.0\bin>mysql -uroot -ppassword < d:/admindb/aar.sql When i do this manually in cmd, i am getting my results. Now i am trying to do this programatically, to execute it in cmd from c# code. I am using the below code to do it. I am not getting any errors and Result !!! When i debug, i get the value of string commandLine as below, "\"C:\\MySQL\\MySQL Server 5.0\\bin\\\" -uroot -ppassword > \"D:/admindb/AAR12.sql" I guess the problem is with this string, passed to cmd. How to solve this ??. public void Execute() { string commandLine = "\"" + MySqlCommandPath + "\"" + " -u" + DbUid + " -p" + DbPwd + " > " + "\"" + Path.Combine(Path_Backup, FileName_Backup + ExcID + ".sql"); System.Diagnostics.ProcessStartInfo PSI = new System.Diagnostics.ProcessStartInfo("cmd.exe"); PSI.RedirectStandardInput = true; PSI.RedirectStandardOutput = true; PSI.RedirectStandardError = true; PSI.UseShellExecute = false; System.Diagnostics.Process p = System.Diagnostics.Process.Start(PSI); System.IO.StreamWriter SW = p.StandardInput; System.IO.StreamReader SR = p.StandardOutput; SW.WriteLine(commandLine); SW.Close(); }

    Read the article

  • Probelem, executing commands in cmd using c#

    - by srk
    I need to execute the below command in command prompt. C:\MySQL\MySQL Server 5.0\bin>mysql -uroot -ppassword < d:/admindb/aar.sql When i do this manually in cmd, i am getting my results. Now i am trying to do this programatically, to execute it in cmd from c# code. I am using the below code to do it. I am not getting any errors and Result !!! When i debug, i get the value of string commandLine as below, "\"C:\\MySQL\\MySQL Server 5.0\\bin\\\" -uroot -ppassword > \"D:/admindb/AAR12.sql" I guess the problem is with this string, passed to cmd. How to solve this ??. public void Execute() { string commandLine = "\"" + MySqlCommandPath + "\"" + " -u" + DbUid + " -p" + DbPwd + " > " + "\"" + Path.Combine(Path_Backup, FileName_Backup + ExcID + ".sql"); System.Diagnostics.ProcessStartInfo PSI = new System.Diagnostics.ProcessStartInfo("cmd.exe"); PSI.RedirectStandardInput = true; PSI.RedirectStandardOutput = true; PSI.RedirectStandardError = true; PSI.UseShellExecute = false; System.Diagnostics.Process p = System.Diagnostics.Process.Start(PSI); System.IO.StreamWriter SW = p.StandardInput; System.IO.StreamReader SR = p.StandardOutput; SW.WriteLine(commandLine); SW.Close(); }

    Read the article

  • How do you program a windows service in C# to start an application for a user?

    - by Swoop
    Is it possible to start a program so that it is available to a user with a windows service? I have been working with the Process.Start() in C#. I can get the service to kickoff some sort of process that appears in the Task Manager list under processes. However, the program nevers appears on the screen. By default, it runs under the user name "SYSTEM". I have adjusted the "Log On" option in the service manager to match the person logged into the computer, but this does not cause a window to appear either. I feel like I am either missing a simple setting, or need to take a different direction for this. Below is the code I have been working with to start up Firefox as a test app. private void startRunDap() { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "Firefox"; startInfo.WindowStyle = ProcessWindowStyle.Normal; startInfo.UseShellExecute = true; Process.Start(startInfo); //Process.Start("Firefox"); }

    Read the article

  • Creating a process in ASP.NET MVC controller

    - by GRKamath
    I have a requirement to run an application through my MVC controller. To get the installation path I used following link (I used answer provided by Fredrik Mörk). It worked and I could able to run the exe through a process. The problem occurred when I deployed this solution on IIS where it did not create the process as it was creating in local dev environment. Can anybody tell me how to create a windows process through a solution which is hosted on IIS ? private string GetPathForExe(string fileName) { private const string keyBase = @"SOFTWARE\Wow6432Node\MyApplication"; RegistryKey localMachine = Registry.LocalMachine; RegistryKey fileKey = localMachine.OpenSubKey(string.Format(@"{0}\{1}", keyBase, fileName)); object result = null; if (fileKey != null) { result = fileKey.GetValue("InstallPath"); } fileKey.Close(); return (string)result; } public void StartMyApplication() { Process[] pname = Process.GetProcessesByName("MyApplication"); if (pname.Length == 0) { string appDirectory = GetPathForExe("MyApplication"); Directory.SetCurrentDirectory(appDirectory); ProcessStartInfo procStartInfo = new ProcessStartInfo("MyApplication.exe"); procStartInfo.WindowStyle = ProcessWindowStyle.Hidden; Process proc = new Process(); proc.StartInfo = procStartInfo; proc.Start(); } }

    Read the article

  • Detect Application Shutdown in C# NET?

    - by Michael Pfiffer
    I am writing a small console application (will be ran as a service) that basically starts a Java app when it is running, shuts itself down if the Java app closes, and shuts down the Java app if it closes. I think I have the first two working properly, but I don't know how to detect when the .NET application is shutting down so that I can shutdown the Java app prior to that happening. Google search just returns a bunch of stuff about detecting Windows shutting down. Can anyone tell me how I can handle that part and if the rest looks fine? namespace MinecraftDaemon { class Program { public static void LaunchMinecraft(String file, String memoryValue) { String memParams = "-Xmx" + memoryValue + "M" + " -Xms" + memoryValue + "M "; String args = memParams + "-jar " + file + " nogui"; ProcessStartInfo processInfo = new ProcessStartInfo("java.exe", args); processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; try { using (Process minecraftProcess = Process.Start(processInfo)) { minecraftProcess.WaitForExit(); } } catch { // Log Error } } static void Main(string[] args) { Arguments CommandLine = new Arguments(args); if (CommandLine["file"] != null && CommandLine["memory"] != null) { // Launch the Application LaunchMinecraft(CommandLine["file"], CommandLine["memory"]); } else { LaunchMinecraft("minecraft_server.jar", "1024"); } } } }

    Read the article

  • Executing a process in windows server 2003 and ii6 from code - permissions error

    - by kurupt_89
    I have a problem executing a process from our testing server. On my localhost using windows XP and iis5.1 I changed the machine.config file to have the line - I then changed the login for iis to log on as local system account and allow server to interact with desktop. This fixed my problem executing a process from code in xp. When using the same method on windows server 2003 (using iis6 isolation mode) the process does not get executed. Here is the code to execute the process (I have tested the inputs to iecapt through the command line and an image is generated) - public static void GenerateImageToDisk(string ieCaptPath, string url, string path, int delay) { url = FixUrl(url); ieCaptPath = FixPath(ieCaptPath); string arguments = @"--url=""{0}"" --out=""{1}"" --min-width=0 --delay={2}"; arguments = string.Format(arguments, url, path, delay); ProcessStartInfo ieCaptProcessStartInfo = new ProcessStartInfo(ieCaptPath + "IECapt.exe"); ieCaptProcessStartInfo.RedirectStandardOutput = true; ieCaptProcessStartInfo.WindowStyle = ProcessWindowStyle.Hidden; ieCaptProcessStartInfo.UseShellExecute = false; ieCaptProcessStartInfo.Arguments = arguments; ieCaptProcessStartInfo.WorkingDirectory = ieCaptPath; Process ieCaptProcess = Process.Start(ieCaptProcessStartInfo); ieCaptProcess.WaitForExit(600000); ieCaptProcess.Close(); }

    Read the article

  • How change encoding ?

    - by simply denis
    I need convert or set encoding windows-1251 Process p = new Process(); StreamWriter sw; StreamReader sr; StreamReader err; ProcessStartInfo psI = new ProcessStartInfo("cmd"); psI.UseShellExecute = false; psI.RedirectStandardInput = true; psI.RedirectStandardOutput = true; psI.RedirectStandardError = true; psI.CreateNoWindow = true; p.StartInfo = psI; p.Start(); sw = p.StandardInput; sr = p.StandardOutput; err = p.StandardError; sw.AutoFlush = true; if (tbComm.Text != "") sw.WriteLine(tbComm.Text); else //execute default command sw.WriteLine("dir \\"); sw.Close(); textBox1.Text = sr.ReadToEnd();// this not support russian word. I need convert or set encoding windows-1251 textBox1.Text += err.ReadToEnd();

    Read the article

  • Executing sc.exe from .NET Process unable to start and stop service.

    - by Jason
    I'm trying to restart the service from a remote machine. Here is my code. The problem is that I need to enter startinfo.filename = "sc.exe" since I'm putting "start /wait sc" this is causing an error. Here is my code, any thoughts. Also if anyone has any idea how to keep the cmd window open after this is ran so I could see the code that was ran that would be awesome. string strCommandStop1; string strCommandStop2; string strCommandStart1; string strCommandStart2; string strServer = "\\" + txtServerName.Text; string strDb1 = "SqlAgent$" + txtInsName.Text; string strDb2 = "MSSQL$" + txtInsName.Text; strCommandStop1 = @"start /wait sc " + strServer + " Stop " + strDb1; strCommandStop2 = @"start /wait sc " + strServer + " Stop " + strDb2; strCommandStart1 = @"start /wait sc " + strServer + " Start " + strDb2; strCommandStart2 = @"start /wait sc " + strServer + " Start " + strDb1; try { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = true; startInfo.Arguments = strCommandStop1; startInfo.Arguments = strCommandStop2; startInfo.Arguments = strCommandStart1; startInfo.Arguments = strCommandStart2; startInfo .FileName = "sc.exe"; Process.Start(startInfo); } catch (Exception e) { MessageBox.Show(e.Message); }

    Read the article

  • Why does Chrome not start correctly when using C# Process.Start?

    - by nbolton
    I'm able to start Chrome successfully using this C# code: Process.Start("chrome", "http://www.google.co.uk"); However, it does two things wrong: It does not navigate to the URL specified in arguments It does not re-use the existing Chrome window (it opens a new one) I've tried using ProcessStartInfo and setting UseShellExecute and LoadUserProfile just in case these did something, but this makes no difference. Any ideas?

    Read the article

  • Programatically Gathering NUnit results

    - by skb
    Hi. I am running some NUnit tests automatically when my nightly build completes. I have a console application which detects the new build, and then copies the built MSI's to a local folder, and deploys all of my components to a test server. After that, I have a bunch of tests in NUnit dll's that I run by executing "nunit-console.exe" using Process/ProcessStartInfo. My question is, how can programatically I get the numbers for Total Success/Failed tests?

    Read the article

  • Best way to run remote VBScript in ASP.net? WMI or PsExec?

    - by envinyater
    I am doing some research to find out the best and most efficient method for this. I will need to execute remote scripts on a number of Window Servers/Computers (while we are building them). I have a web application that is going to automate this task, I currently have my prototype working to use PsExec to execute remote scripts. This requires PsExec to be installed on the system. A colleague suggested I should use WMI for this. I did some research in WMI and I couldn't find what I'm looking for. I want to either upload the script to the server and execute it and read the results, or already have the script on the server and execute it and read the results. I would prefer the first option though! Which is more ideal, PsExec or WMI? For reference, this is my prototype PsExec code. This script is only executing a small script to get the Windows OS and Service Pack Info. Protected Sub windowsScript(ByVal COMPUTERNAME As String) ' Create an array to store VBScript results Dim winVariables(2) As String nameLabel.Text = Name.Text ' Use PsExec to execute remote scripts Dim Proc As New System.Diagnostics.Process ' Run PsExec locally Proc.StartInfo = New ProcessStartInfo("C:\Windows\psexec.exe") ' Pass in following arguments to PsExec Proc.StartInfo.Arguments = COMPUTERNAME & " -s cmd /C c:\systemInfo.vbs" Proc.StartInfo.RedirectStandardInput = True Proc.StartInfo.RedirectStandardOutput = True Proc.StartInfo.UseShellExecute = False Proc.Start() ' Pause for script to run System.Threading.Thread.Sleep(1500) Proc.Close() System.Threading.Thread.Sleep(2500) 'Allows the system a chance to finish with the process. Dim filePath As String = COMPUTERNAME & "\TTO\somefile.txt" 'Download file created by script on Remote system to local system My.Computer.Network.DownloadFile(filePath, "C:\somefile.txt") System.Threading.Thread.Sleep(1000) ' Pause so file gets downloaded ''Import data from text file into variables textRead("C:\somefile.txt", winVariables) WindowsOSLbl.Text = winVariables(0).ToString() SvcPckLbl.Text = winVariables(1).ToString() System.Threading.Thread.Sleep(1000) ' ''Delete the file on server - we don't need it anymore Dim Proc2 As New System.Diagnostics.Process Proc2.StartInfo = New ProcessStartInfo("C:\Windows\psexec.exe") Proc2.StartInfo.Arguments = COMPUTERNAME & " -s cmd /C del c:\somefile.txt" Proc2.StartInfo.RedirectStandardInput = True Proc2.StartInfo.RedirectStandardOutput = True Proc2.StartInfo.UseShellExecute = False Proc2.Start() System.Threading.Thread.Sleep(500) Proc2.Close() ' Delete file locally File.Delete("C:\somefile.txt") End Sub

    Read the article

  • Executing command line from windows application

    - by aron
    Hello, i need to execute command line from .NET windows application. I tried with this code but i get error 'C:\Documents' is not recognized as an internal or external command, operable program or batch file. var command ="\"C:\\Documents and Settings\\Administrator\\My Documents\\test.exe\" \"D:\\abc.pdf\" \"C:\\Documents and Settings\\Administrator\\My Documents\\def.pdf\""; var processInfo = new ProcessStartInfo("cmd","/c " + command) { UseShellExecute = false, RedirectStandardError = true, CreateNoWindow = true }; var p = Process.Start(processInfo);

    Read the article

  • Why is `cmd /C` living after it did its job?

    - by acidzombie24
    My question is why does "cmd" exist (idle) in my process after i update my exe? In my code i run this code to update myself and launch var args = string.Format(@"/C ping 1.1.1.1 -n 1 -w 3000 & move /Y ""{0}"" ""{1}"" & ""{1}"" {2}", updateFn, fn, exeargs); new Process() { StartInfo = new ProcessStartInfo(@"cmd", args) { CreateNoWindow = true, UseShellExecute = false } }.Start(); Environment.Exit(0); The idea is i exit right away and have ping stall for 3seconds before trying to replace my current exe with my updated exe. Then i launch with the necessary args The full arg for cmd looks like this /C ping 1.1.1.1 -n 1 -w 3000 & move /Y "c:\path\update" "c:\path\my.exe" & "c:\path\my.exe" exeargs Everything works fine however i see cmd in the taskmanager (looks to be idle) after my process is launched and correctly working. Why?

    Read the article

  • Problem with System.Diagnostics.Process RedirectStandardOutput to appear in Winforms Textbox in real

    - by Jonathan Websdale
    I'm having problems with the redirected output from a console application being presented in a Winforms textbox in real-time. The messages are being produced line by line however as soon as interaction with the Form is called for, nothing appears to be displayed. Following the many examples on both Stackoverflow and other forums, I can't seem to get the redirected output from the process to display in the textbox on the form until the process completes. By adding debug lines to the 'stringWriter_StringWritten' method and writing the redirected messages to the debug window I can see the messages arriving during the running of the process but these messages will not appear on the form's textbox until the process completes. Grateful for any advice on this. Here's an extract of the code public partial class RunExternalProcess : Form { private static int numberOutputLines = 0; private static MyStringWriter stringWriter; public RunExternalProcess() { InitializeComponent(); // Create the output message writter RunExternalProcess.stringWriter = new MyStringWriter(); stringWriter.StringWritten += new EventHandler(stringWriter_StringWritten); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.FileName = "myCommandLineApp.exe"; startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; startInfo.CreateNoWindow = true; startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; using (var pProcess = new System.Diagnostics.Process()) { pProcess.StartInfo = startInfo; pProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(RunExternalProcess.Process_OutputDataReceived); pProcess.EnableRaisingEvents = true; try { pProcess.Start(); pProcess.BeginOutputReadLine(); pProcess.BeginErrorReadLine(); pProcess.WaitForExit(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { pProcess.OutputDataReceived -= new System.Diagnostics.DataReceivedEventHandler(RunExternalProcess.Process_OutputDataReceived); } } } private static void Process_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { RunExternalProcess.OutputMessage(e.Data); } } private static void OutputMessage(string message) { RunExternalProcess.stringWriter.WriteLine("[" + RunExternalProcess.numberOutputLines++.ToString() + "] - " + message); } private void stringWriter_StringWritten(object sender, EventArgs e) { System.Diagnostics.Debug.WriteLine(((MyStringWriter)sender).GetStringBuilder().ToString()); SetProgressTextBox(((MyStringWriter)sender).GetStringBuilder().ToString()); } private delegate void SetProgressTextBoxCallback(string text); private void SetProgressTextBox(string text) { if (this.ProgressTextBox.InvokeRequired) { SetProgressTextBoxCallback callback = new SetProgressTextBoxCallback(SetProgressTextBox); this.BeginInvoke(callback, new object[] { text }); } else { this.ProgressTextBox.Text = text; this.ProgressTextBox.Select(this.ProgressTextBox.Text.Length, 0); this.ProgressTextBox.ScrollToCaret(); } } } public class MyStringWriter : System.IO.StringWriter { // Define the event. public event EventHandler StringWritten; public MyStringWriter() : base() { } public MyStringWriter(StringBuilder sb) : base(sb) { } public MyStringWriter(StringBuilder sb, IFormatProvider formatProvider) : base(sb, formatProvider) { } public MyStringWriter(IFormatProvider formatProvider) : base(formatProvider) { } protected virtual void OnStringWritten() { if (StringWritten != null) { StringWritten(this, EventArgs.Empty); } } public override void Write(char value) { base.Write(value); this.OnStringWritten(); } public override void Write(char[] buffer, int index, int count) { base.Write(buffer, index, count); this.OnStringWritten(); } public override void Write(string value) { base.Write(value); this.OnStringWritten(); } }

    Read the article

  • Logging Output of Azure Startup Tasks to the Event Log

    - by Your DisplayName here!
    This can come in handy when troubleshooting: using System; using System.Diagnostics; using System.Text;   namespace Thinktecture.Azure {     class Program     {         static EventLog _eventLog = new EventLog("Application", ".", "StartupTaskShell");         static StringBuilder _out = new StringBuilder(64);         static StringBuilder _err = new StringBuilder(64);           static int Main(string[] args)         {             if (args.Length != 1)             {                 Console.WriteLine("Invalid arguments: " + String.Join(", ", args));                 _eventLog.WriteEntry("Invalid arguments: " + String.Join(", ", args));                                 return -1;             }               var task = args[0];               ProcessStartInfo info = new ProcessStartInfo()             {                 FileName = task,                 WorkingDirectory = Environment.CurrentDirectory,                 UseShellExecute = false,                 ErrorDialog = false,                 CreateNoWindow = true,                 RedirectStandardOutput = true,                 RedirectStandardError = true             };               var process = new Process();             process.StartInfo = info;               process.OutputDataReceived += (s, e) =>                 {                     if (e.Data != null)                     {                         _out.AppendLine(e.Data);                     }                 };             process.ErrorDataReceived += (s, e) =>                 {                     if (e.Data != null)                     {                         _err.AppendLine(e.Data);                     }                 };               process.Start();             process.BeginOutputReadLine();             process.BeginErrorReadLine();             process.WaitForExit();               var outString = _out.ToString();             var errString = _err.ToString();               if (!string.IsNullOrWhiteSpace(outString))             {                 outString = String.Format("Standard Out for {0}\n\n{1}", task, outString);                 _eventLog.WriteEntry(outString, EventLogEntryType.Information);             }               if (!string.IsNullOrWhiteSpace(errString))             {                 errString = String.Format("Standard Err for {0}\n\n{1}", task, errString);                 _eventLog.WriteEntry(errString, EventLogEntryType.Error);             }               return 0;         }     } } You then wrap your startup tasks with the StartupTaskShell and you’ll be able to see stdout and stderr in the application event log.

    Read the article

  • Packaging LAME.exe with a C# project

    - by user347821
    Please forgive my noob-ness on this, but how do I package LAME.exe w/ a C# setup project? Currently, I have LAME being called like: //use stringbuilder to create arguments var psinfo = new ProcessStartInfo( @"lame.exe") { Arguments = sb.ToString(), WorkingDirectory = Application.StartupPath, WindowStyle = ProcessWindowStyle.Hidden }; var p = Process.Start( psinfo ); p.WaitForExit(); This works in debug and release modes on the development machine, but when I create a setup project for this, it never creates the MP3. LAME and the compiled code reside in the same directory when installed. Help!

    Read the article

  • Need help regarding Async and fsi

    - by Stringer Bell
    I'd like to write some code that runs a sequence of F# scripts (.fsx). The thing is that I could have literally hundreds of scripts and if I do that: let shellExecute program args = let startInfo = new ProcessStartInfo() do startInfo.FileName <- program do startInfo.Arguments <- args do startInfo.UseShellExecute <- true do startInfo.WindowStyle <- ProcessWindowStyle.Hidden //do printfn "%s" startInfo.Arguments let proc = Process.Start(startInfo) () scripts |> Seq.iter (shellExecute "fsi") it could stress too much my 2GB system. Anyway, I'd like to run scripts by batch of n, which seems also a good exercise for learning Async (I guess it's the way to go). I have written some code and unfortunately it doesn't work: open System.Diagnostics let p = shellExecute "fsi" @"C:\Users\Stringer\foo.fsx" async { let! exit = Async.AwaitEvent p.Exited do printfn "process has exited" } |> Async.StartImmediate foo.fsx is just a hello world script. I'd like also to figure out if it's doable to retrieve a return code for each executing script and if not, find another way. Thanks!

    Read the article

  • Use relative Path in Microsoft Surface application?

    - by Roflcoptr
    I convert my wave file into a mp3 file by the following code: internal bool convertToMp3() { string lameEXE = @"C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Concept_2\Prototype_Concept_2\lame\lame.exe"; string lameArgs = "-V2"; string wavFile = fileName; string mp3File = fileName.Replace("wav", "mp3"); Process process = new Process(); process.StartInfo = new ProcessStartInfo(); process.StartInfo.FileName = lameEXE; process.StartInfo.Arguments = string.Format("{0} {1} {2}", lameArgs, wavFile, mp3File); process.Start(); process.WaitForExit(); int exitCode = process.ExitCode; if (exitCode == 0) { return true; } else { return false; } } This works, but now I'd like to not use the absolut path to the lame.exe but a relative path. I included a lame.exe in the folder /lame/ on the root of the project. How can I reference it?

    Read the article

  • accesing local exe file from asp.net application

    - by sansknwoledge
    hi, i am having a intranet asp.net application , all the clients connected to it is having a specific .exe file in their local disk, now i want to execute the .exe file from the .net application hosted in a intranet server. i used this code to do that Dim psi As New System.Diagnostics.ProcessStartInfo() psi.WorkingDirectory = "C:\\" psi.FileName = "c:\\Project1.exe" '"file:///c:/Project1.exe" psi.Arguments = iApqpId 'cTimeMaster.APQPID psi.UseShellExecute = False System.Diagnostics.Process.Start(psi) but it is throwing a error the system cannot find the file specified. is it having a permission issue on local system or any thing else, any help would be greatly appriciated. thanks and regards

    Read the article

  • handle exit event of child process

    - by Ehsan
    I have a console application and in the Main method. I start a process like the code below, when process exists, the Exist event of the process is fired but it closed my console application too, I just want to start a process and then in exit event of that process start another process. It is also wired that process output is reflecting in my main console application. Process newCrawler = new Process(); newCrawler.StartInfo = new ProcessStartInfo(); newCrawler.StartInfo.FileName = configSection.CrawlerPath; newCrawler.EnableRaisingEvents = true; newCrawler.Exited += new EventHandler(newCrawler_Exited); newCrawler.StartInfo.Arguments = "someArg"; newCrawler.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; newCrawler.StartInfo.UseShellExecute = false; newCrawler.Start();

    Read the article

< Previous Page | 1 2 3 4  | Next Page >