I have been working on converting a GUI script from another language to C# in VS2017 for a customer. With help from the folks here I am 95% of the way there, but have run into a couple of snags; just not sure I am doing things in the best way. I'm including just the relevant portions of code below, please let me know if I am not providing enough:
The majority of the code is centered on the wpf form, which collects data for low level technicians to batch deploy a number of Virtual Machines into the VMware environment. This number could easily range into the dozens or even a hundred VMs at once. The information for each VM is specified in the form, then collected in a listview. Once the listview is fully populated it is exported to a csv. Up to this point everything works just fine.
I've next been working on actually launching the powershell/powerCLI script (also working) and capturing output. The log file is opened with a specific reader application the customer uses, which updates in real time, and the captured output is fed to the log. It is important for the technicians to see the output from the code line by line so they can react if there is an issue.
I started with something like this as a test:
string sPSScript = "C:\\Users\\Admin\\Desktop\\TestC#.ps1";
string logFile = "C:\\Users\\Admin\\Desktop\\My.log";
string logReader = "C:\\Users\\Admin\\Documents\\CMTrace.exe";
string standard_output;
System.Diagnostics.Process PSScript = new System.Diagnostics.Process();
PSScript.StartInfo.FileName =
Environment.GetFolderPath(Environment.SpecialFolder.SystemX86) +
"\\WindowsPowerShell\\v1.0\\powershell.exe";
PSScript.StartInfo.Arguments = "-command . '" + sPSScript + "' " +
vCenter.Text;
PSScript.StartInfo.RedirectStandardOutput = true;
PSScript.StartInfo.UseShellExecute = false;
PSScript.Start();
System.Diagnostics.Process LogFile = new System.Diagnostics.Process();
LogFile.StartInfo.FileName = logReader;
LogFile.StartInfo.Arguments = logFile;
LogFile.Start(); while ((standard_output =
PSScript.StandardOutput.ReadLine()) != null)
{
if (standard_output != "")
{
using (StreamWriter file = new StreamWriter(logFile, append: true))
{
file.WriteLine(standard_output);
}
}
}
While this writes to the log file in real time as expected, it creates 100 instances of the logReader application. I understand why, since I am declaring a new StreamWriter object through every pass, but am unsure how better to go about this.
I tried creating the file outside the loop, like this:
StreamWriter file = new StreamWriter(logFile, append: true) { };
System.Diagnostics.Process LogFile = new System.Diagnostics.Process();
LogFile.StartInfo.FileName = logReader;
LogFile.StartInfo.Arguments = logFile;
System.Diagnostics.Process PSScript = new System.Diagnostics.Process();
PSScript.StartInfo.FileName = Environment.GetFolderPath(Environment.SpecialFolder.SystemX86) + "\\WindowsPowerShell\\v1.0\\powershell.exe";
PSScript.StartInfo.Arguments = "-command . '" + sPSScript + "' " + vCenter.Text;
PSScript.StartInfo.RedirectStandardOutput = true;
PSScript.StartInfo.UseShellExecute = false;
LogFile.Start();
PSScript.Start();
System.Threading.Thread.Sleep(1500);
while ((standard_output = PSScript.StandardOutput.ReadLine()) != null)
{
if (standard_output != "")
{
file.WriteLine(standard_output);
}
}
It doesn't create multiple instances, but it also does not update the log file in real time as the previous code does. It only updates once the script runs, and then only partially. The script produces ~1000 lines of output, and I consistently see only about 840 written to the log file.
I thought about doing something like this:
FileStream logFS;
logFS = new FileStream(logFile, FileMode.Append);
but it appears the only options available to me to write to the file are expecting a byte array.
I am sure that I am missing something stupid simple in this, but would appreciate any suggestions on the easiest way to create the log file, open it in the reader, and then update it with the standard output from the powershell script.
why did the previous code writes in real time?
because you are wrapping it with using. And at the end of using block its gonna call dispose which calls .Flush to write to disk
Your second code block calls WriteLine but never called Flush so it writes to the disk whenever the buffer is full. Just add a .Flush call after WriteLine and you will have real time logging
Related
I have this question,
My boss wants a program which you can enter a path, Console.ReadLine(directory);
This is irrelevant, I got this part working. In fact, the whole code/program is working as it should be.
The point of the path is that the program scans all the files in the given directory/subdirectories for the last write time. He want to pay minimum effort in this. So the plan is to use Windows to start this program once every 24 hours.
Only problem with this "minimum effort" part is that you have to enter the path EVERYTIME when it's started. So it actually doesn't go automaticly.
The question is: is there a way to avoid this?
For example Thread.Sleep(); and when it's done sleeping goto a label right under the Console.ReadLine(directory);?
So not once a day, but sleeping for 24 hours and for 1 whole minute working?
If it's any help, here's the code:
using System.IO;
using System.Security.Permissions;
namespace CheckWithinTime
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Which folder do you wish to scan?");
string path = Console.ReadLine();
//copies everything from the console to a .txt file
FileStream filestream = new FileStream(#"C:\Logs\Log.txt", FileMode.Create);
var streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);
//this is the path which you type in a the beginning of the program
string[] files = Directory.GetFiles(path, "*.*", System.IO.SearchOption.AllDirectories);
List<string> updatedFiles = new List<string>();
DateTime from = DateTime.Now.AddDays(-1);
DateTime to = DateTime.Now;
foreach (string name in files)
{
FileInfo file = new FileInfo(name);
string fullname = file.FullName;
//checks if the last writed time occured less then 24 hours ago, if it's not it will not be loggeed
if (file.LastWriteTime >= from && file.LastWriteTime <= to)
{
updatedFiles.Add(name);
Console.WriteLine(file.FullName + " ; " + "last changed at >> " + " ; " + file.LastWriteTime.ToString());
//Console.WriteLine("File created at >> " + file.CreationTime.ToString());
//Console.WriteLine("File last opened at >> " + file.LastAccessTime.ToString());
Console.WriteLine();
}
}
streamwriter.Close();
filestream.Close();
//The mail class basicly sends an e-mail to the server with the log file, but this is irrelevant
Mail();
}
}
}
It used to be just a simple file system watcher. After that it was like it is now, but without the Console.ReadLine() part. And now he wants to give a path.
If anyone can tell me a way to avoid the Console.ReadLine(), but only use call it when you need it. I would appreciate it!
Sorry in advance for my big texts.
The best way to do this would be to either create an XML file or use a notepad file and have windows run a task manager.
You can set up a program to run every so often in windows task manager and all you need to do is save the path to a file and have your C# console application read that file and get the path, the path will always be store and the program will run all the time.
We do this at work; a program has been running for 4 months doing through a bunch of paths and we don't edit it anymore.
Xml file/config is overkill for one setting. Pass it in to the command line string[] args:
string path;
if(args.Length > 0)
{
path = args[0];
Console.WriteLine("Using path: " + path);
}
else
{
Console.WriteLine("Which folder do you wish to scan?");
path = Console.ReadLine();
}
Then use task scheduler as already suggested, but pass the path as a command line argument. You can also then launch it with different paths without your app supporting multiple paths.
First of all, sorry that I was unable to give a proper title.
I got stuck with an idea that's been with me today almost the whole day after searching and searching and searching, till it came to a point that I decided to ask it on Stackoverflow!
So here's where I am stuck:
(I am making an auto-installer currently coded in C# and it is Dutch. It works really awesome but I just need one thing to finish my base. For example:
You have 'multiple' objects selected in a checklistbox, those are read from the checklistbox itself, they get trimmed and they get launched after that.
Now that's all working, I wanted to add a waiting method, for example we got:
Malwarebytes & CCleaner as installation 'example'.
Now when both are checked, and I click start, it starts both of the programs.
What I want to do is: to tell the program to start one program, do your thing, once its finished (closed) it should go to the next.
But... There is a problem, my programs are started in an array, so it basically works if there are multiple objects checked, than it will start all of the checked objects. And I really have no idea how to reach the same thing which is basically :
If there are multiple objects selected, start the object(s), do your thing(auto-clicking etc.),once its closed and confirmed its closed, move on to the next object and do the same thing until its been completed. I would like to make it work with a progressbar, but never really looked into a progress bar as they seem confusing.
I have a piece of code that finds the Process ID so maybe I can do something with that, but the Process ID is never the same on the applications that I start, so when they start in an array I got kinda of an issue.
Could someone help me please figuring out what & how to code / do this?
here's the code i use to make this work :
string pad = Application.StartupPath;
foreach (string checkedItem in checkedListBox1.CheckedItems)
{
if (checkedItem.Contains("."))
{
string str = checkedItem;
if (str.Contains("."))
{
int index = str.IndexOf('.');
string folder = str.Substring(0, index);
try
{
bool started = false;
var process = new Process();
process.StartInfo.FileName = pad + "/data/" + folder + "/" + checkedItem;
started = process.Start();
var processID = process.Id;
var processNAAM = process.ProcessName;
textBox1.Text += "Gevonden - ID: " + processID + " NAAM: " + processNAAM + Environment.NewLine;
textBox1.Text += DateTime.Now.ToString("HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo) + " - " + "Installatie Keuze wordt opgestart." + Environment.NewLine;
process.WaitForExit();
}
catch (Exception)
{
}
}
}
}
First of all, you can make the code simpler and shorter by using the CheckedListBox's CheckedItems property. Secondly, there's no point to all your copying of strings from one to another. Strings are immutable in .NET - they never change. You can keep just one copy and cut from there.
Next, you can use the methods in System.IO.Path to cut the filename without the extension, or to build a full path without worrying about having too many or too few "/"'s.
Third, for your original question - just call WaitForExit on your Process object to make it wait before moving on with the list of processes.
Thirdly
foreach (string checkedItem in checkedListBox1.CheckedItems)
{
if (checkedItem.Contains("."))
{
string baseName = Path.GetFileNameWithoutExtension(checkedItem);
string processPath = Path.Combine(pad, "data", baseName, checkedItem);
Process process = Process.Start(processPath);
process.WaitForExit();
}
}
After the line where you start the process (process.Start()), simply add the following:
process.WaitForExit()
This will pause the containing thread until the target process has exited.
I have a console application and I want to process the std out in a c# application.
Basically I already managed to do this with this code:
Process ProcessObj = new Process();
ProcessObj.StartInfo.WorkingDirectory = WorkingPath;
ProcessObj.StartInfo.FileName = ApplicationPath;
ProcessObj.StartInfo.Arguments = ApplicationArguments;
ProcessObj.StartInfo.UseShellExecute = false;
ProcessObj.StartInfo.CreateNoWindow = true;
ProcessObj.StartInfo.RedirectStandardOutput = true;
// Start the process
ProcessObj.Start();
// loop through until the job is done
bool stopper = false;
while (!stopper)
{
stopper = ProcessObj.WaitForExit(100);
string line = null;
// handle normal outputs (loop through the lines)
while (true)
{
line = ProcessObj.StandardOutput.ReadLine();
if (line == null)
break;
Logger.Trace("Out: \"" + line + "\"");
}
}
When the process runs only a few seconds it looks like the whole thing is working without any problem. When I change the configuration of the console application to calculate more, it comes that the process is running for hours. In this time my C# application gets no response from the console app. Since the console app is hidden it looks like the app stucked but that's not true. It is already running in the background and it seems that all std outputs are only piped through to my c# app when the console app was finished the execution.
So the problem is, I don't see the std out lines live in my c# app. It will be refreshed after hours when the console app has finished.
Is there any way to flush this std out redirection?
Anybody knows why this isn't working like I want?
PS: When I execute the console app as standalone in a normal cmd window the outputs are shown live without any problem.
Please help.
Try and read the output while the application is running? And save it to a buffer? Then process the output when the application exits.
pseudo stuff
string buffer = string.Empty;
while(!process.HasExited)
{
string line = process.Stream.ReadLine();
if (line != null)
buffer += Enviorment.Newline + line
}
// Do stuff without put here
Console.Write(buffer);
i want to launch ffmpeg from my app and retrive all console output that ffmpeg produces. Thing seems obvious, i followed many forum threads/articles like this one but i have problem, though i follow all information included there I seem to end up in dead end.
String that should contain output from ffmpeg is always empty. I've tried to see where is the problem so i made simple c# console application that only lists all execution parameters that are passed to ffmpeg, just to check if problem is caused by ffmpeg itself. In that case everything work as expected.
I also did preview console window of my app. When i launch ffmpeg i see all the output in console but the function that should recieve that output for further processing reports that string was empty. When my param-listing app is launched the only thing I see is the expected report from function that gets output.
So my question is what to do to get ffmpeg output as i intended at first place.
Thanks in advance
MTH
This is a long shot, but have you tried redirecting StandardError too?
Here is a part of my ffmpeg wrapper class, in particular showing how to collect the output and errors from ffmpeg.
I have put the Process in the GetVideoDuration() function just so you can see everything in the one place.
Setup:
My ffmpeg is on the desktop, ffPath is used to point to it.
namespace ChildTools.Tools
{
public class FFMpegWrapper
{
//path to ffmpeg (I HATE!!! MS special folders)
string ffPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ffmpeg.exe";
//outputLines receives each line of output, only if they are not zero length
List<string> outputLines = new List<string>();
//In GetVideoDuration I only want the one line of output and in text form.
//To get the whole output just remove the filter I use (my search for 'Duration') and either return the List<>
//Or joint the strings from List<> (you could have used StringBuilder, but I find a List<> handier.
public string GetVideoDuration(FileInfo fi)
{
outputLines.Clear();
//I only use the information flag in this function
string strCommand = string.Concat(" -i \"", fi.FullName, "\"");
//Point ffPath to my ffmpeg
string ffPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ffmpeg.exe";
Process processFfmpeg = new Process();
processFfmpeg.StartInfo.Arguments = strCommand;
processFfmpeg.StartInfo.FileName = ffPath;
//I have to say that I struggled for a while with the order that I setup the process.
//But this order below I know to work
processFfmpeg.StartInfo.UseShellExecute = false;
processFfmpeg.StartInfo.RedirectStandardOutput = true;
processFfmpeg.StartInfo.RedirectStandardError = true;
processFfmpeg.StartInfo.CreateNoWindow = true;
processFfmpeg.ErrorDataReceived += processFfmpeg_OutData;
processFfmpeg.OutputDataReceived += processFfmpeg_OutData;
processFfmpeg.EnableRaisingEvents = true;
processFfmpeg.Start();
processFfmpeg.BeginOutputReadLine();
processFfmpeg.BeginErrorReadLine();
processFfmpeg.WaitForExit();
//I filter the lines because I only want 'Duration' this time
string oStr = "";
foreach (string str in outputLines)
{
if (str.Contains("Duration"))
{
oStr = str;
}
}
//return a single string with the duration line
return oStr;
}
private void processFfmpeg_OutData(object sender, DataReceivedEventArgs e)
{
//The data we want is in e.Data, you must be careful of null strings
string strMessage = e.Data;
if outputLines != null && strMessage != null && strMessage.Length > 0)
{
outputLines.Add(string.Concat( strMessage,"\n"));
//Try a Console output here to see all of the output. Particularly
//useful when you are examining the packets and working out timeframes
//Console.WriteLine(strMessage);
}
}
}
}
Right what im trying to accomplish is a program that basically sets the active partition in 1 click, saving the effort time and skill of using cmd prompt etc.
I have looked into the System.Management name space but couldn't work out how to use it :(
So i have resorted to using CMD, i have got a module application written in C# and basically i want to run "DISKPART" which then starts the diskpart in the cmd window, then i want to ask it to "Select disk 0" followed by "select partition 1" finally followed by "active".
Doing this in CMD yourself works fine but with an application its proved to be awkward :( What ive managed to get it to do is run DiskPart fine in one window with Process.Start, then get it to open a new window and run the next piece of code but because the new window hasnt ran the diskpart cmd it doesnt work >:(
Any suggestions?
Thanks!
Ash
As long as you aren't making decisions on the output, you could build a batch file in your C# app and start that via Process.Start(...).
You'll need to generate two files.
First runDiskPart.bat:
diskpart /s myScript.dp
Second myScript.dp:
...some commands...
exit
Obviously the names are completely arbitrary but the /s directive needs to reference the name of your second file.
After some searching, I think you can do what you want with a script file. Read this.
You can therefore run diskpart /s script.txt with Process.Start after creating a script.txt file with your necessary commands.
This may be a bit of a read so im sorry in advance. And this is my tried and tested way of doing this, there may be a simpler way but this is from me throwing code at a wall and seeing what stuck
TLDR code for this question in particular
Ok sorry This one is actually not tested. this one IN THEORY works
public static void ChangeMe()
{
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string path1 = docPath + "\\Test.txt";
string path2 = docPath + "\\Test.bat";
string[] lines =
{
"select disk 0",
"clean",
"convert gpt",
"create partition primary size=300",
"format quick fs=ntfs label=Windows RE tools",
"assign letter=T"
};
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.txt")))
{
foreach (string line in lines)
outputFile.WriteLine(line);
}
string[] lines =
{
"diskpart /s test.txt"
};
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
{
foreach (string line in lines)
outputFile.WriteLine(line);
}
System.Diagnostics.Process.Start(path2);
}
If what you want to do be can be done in batch file, then the maybe over complicated work around is have c# write a .bat file and run it. If you want user input you could place the input into a variable and have c# write it into the file. it will take trial and error with this way because its like controlling a puppet with another puppet. And with Diskpart its a little more complicated because you have to make 2 files one that is a .bat and one that is a txt.
here is an example for just a batch file, In this case the function is for a push button in windows forum app that clears the print queue.
using System.IO;
using System;
public static void ClearPrintQueue()
{
//this is the path the document or in our case batch file will be placed
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//this is the path process.start usues
string path1 = docPath + "\\Test.bat";
// these are the batch commands
// remember its "", the comma separates the lines
string[] lines =
{
"#echo off",
"net stop spooler",
"del %systemroot%\\System32\\spool\\Printers\\* /Q",
"net start spooler",
//this deletes the file
"del \"%~f0\"" //do not put a comma on the last line
};
//this writes the string to the file
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
{
//This writes the file line by line
foreach (string line in lines)
outputFile.WriteLine(line);
}
System.Diagnostics.Process.Start(path1);
}
IF you want user input then you could try something like this.
This is for setting the computer IP as static but asking the user what the IP, gateway, and dns server is.
you will need this for it to work
public static void SetIPStatic()
{
//These open pop up boxes which ask for user input
string STATIC = Microsoft.VisualBasic.Interaction.InputBox("Whats the static IP?", "", "", 100, 100);
string SUBNET = Microsoft.VisualBasic.Interaction.InputBox("Whats the Subnet?(Press enter for default)", "255.255.255.0", "", 100, 100);
string DEFAULTGATEWAY = Microsoft.VisualBasic.Interaction.InputBox("Whats the Default gateway?", "", "", 100, 100);
string DNS = Microsoft.VisualBasic.Interaction.InputBox("Whats the DNS server IP?(Input required, 8.8.4.4 has already been set as secondary)", "", "", 100, 100);
//this is the path the document or in our case batch file will be placed
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//this is the path process.start usues
string path1 = docPath + "\\Test.bat";
// these are the batch commands
// remember its "", the comma separates the lines
string[] lines =
{
"SETLOCAL EnableDelayedExpansion",
"SET adapterName=",
"FOR /F \"tokens=* delims=:\" %%a IN ('IPCONFIG ^| FIND /I \"ETHERNET ADAPTER\"') DO (",
"SET adapterName=%%a",
"REM Removes \"Ethernet adapter\" from the front of the adapter name",
"SET adapterName=!adapterName:~17!",
"REM Removes the colon from the end of the adapter name",
"SET adapterName=!adapterName:~0,-1!",
//the variables that were set before are used here
"netsh interface ipv4 set address name=\"!adapterName!\" static " + STATIC + " " + STATIC + " " + DEFAULTGATEWAY,
"netsh interface ipv4 set dns name=\"!adapterName!\" static " + DNS + " primary",
"netsh interface ipv4 add dns name=\"!adapterName!\" 8.8.4.4 index=2",
")",
"ipconfig /flushdns",
"ipconfig /registerdns",
":EOF",
"DEL \"%~f0\"",
""
};
//this writes the string to the file
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
{
//This writes the file line by line
foreach (string line in lines)
outputFile.WriteLine(line);
}
System.Diagnostics.Process.Start(path1);
}
Like I said. It may be a little overcomplicated but it never fails unless I write the batch commands wrong.
This is the code for diskpart. You have to understand the command prompt in order to get these to work. With diskpart you cannot just write a script like
diskpart
select disk 0
clean
convert gpt
create partition primary size=300
format quick fs=ntfs label=Windows RE tools
assign letter=T
This is because diskpart opens its own window and the rest of the commands just throw errors in the command prompt window
so you have to get c# to first write a text file with the commands. Then a batch file with the diskpart command to call the text file that you just wrote.
As I said at first This one is actually not tested. this one IN THEORY works
public static void ChangeMe()
{
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string path1 = docPath + "\\Test.txt";
string path2 = docPath + "\\Test.bat";
string[] lines =
{
"select disk 0",
"clean",
"convert gpt",
"create partition primary size=300",
"format quick fs=ntfs label=Windows RE tools",
"assign letter=T"
};
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.txt")))
{
foreach (string line in lines)
outputFile.WriteLine(line);
}
string[] lines =
{
"diskpart /s test.txt"
};
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
{
foreach (string line in lines)
outputFile.WriteLine(line);
}
System.Diagnostics.Process.Start(path2);
}
What about introducing a delay, such as Thread.Sleep(1000), so that the other process has time to complete the first command?
What you really want to do is wait for the program to exit and then move onto the next invocation. Take a look at this question.