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.
Related
Just a quick question if you can help me, please.
In C#, I am creating a directory, if it does not exist. In the next command, I am checking if the directory exists, I will copy some files.
The Problem is, to creating a new directory or Deleting it, takes time and slower than next code execution time.
The software gives an error of "The folder does not exist ".
I used Thread.Sleep(5000); to wait 5 seconds before copying the content to the directory.
It seems to be working but I feel like that this is not how it's supposed to be done. Does anyone know better coding?
string logDirectoryPath = Directory.GetCurrentDirectory() + "\\LogFiles";
if (!Directory.Exists(logDirectoryPath))
{
Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\LogFiles");
Thread.Sleep(5000);
}
if (Directory.Exists(Directory.GetCurrentDirectory() + "\\LogFiles"))
{
var s = logDirectoryPath + "\\Log_" + DateTime.Now.ToString("dd_MM_yyyy") + ".txt";
using (StreamWriter w = File.AppendText(s))
{
w.WriteLine("--");
w.Write("\r\nLog Entry : ");
w.WriteLine($"{DateTime.Now.ToLongTimeString()} {DateTime.Now.ToLongDateString()}");
}
}
//EDIT
JUST thought maybe I should use a loop?
While(!Directory.Exists(logDirectoryPath))
{
Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\LogFiles");
}
Use DirectoryInfo
DirectoryInfo di = new DirectoryInfo(#{PATHSTRING});
and use di.Exists to check it exists / di.Create() to create folder
and I'd like to recommend to use logDirectoryPath which you defined already.
like this
DirectoryInfo di = new DirectoryInfo(logDirectoryPath);
if ( !di.Exists ) {
di.Create();
}
So, I am running SSIS (through VS) and I have two segments that hang me up when my clients don't send in the exact files every day. I have a task that deletes old files, and then renames the current files to the filename with _OLD at the end of it.
The issue is: If the files that are in there aren't the exact same, it crashes, failing the entire thing.
An example:
A client sends in on Monday files: Names, Addresses, Grades, Schools
The same client, on Tuesday sends in: Names, Addresses, Schools
Since the Grades file doesn't exist, it still gets renamed to Grades_OLD but the SSIS fails.
The scripts are:
del Names_OLD.csv
bye
This will then go to the Rename Script:
ren Names.csv Names_OLD.csv
bye
and will then go on to Addresses, to do the same thing. It is super frustrating that these fail when a single file doesn't exist the next day, and there doesn't seem to be a need for it.
We have two scripts that generate the archive data to process:
public void Main()
{
Dts.Variables["ARCHIVEFILE"].Value = Path.GetFileNameWithoutExtension(Dts.Variables["FTPFILE"].Value.ToString()) + "_OLD" + Path.GetExtension(Dts.Variables["FTPFILE"].Value.ToString());
Dts.TaskResult = (int)ScriptResults.Success;
}
and
public void Main()
{
/*PSFTP_DEL_script.txt
del %1
bye
PSFTP_REN_script.txt
ren %1 %2
bye
*/
var lineOut = String.Empty;
var File1 = Dts.Variables["User::FTPWORKINGDIR"].Value.ToString() + "\\SSIS_PSFTP_DEL_script.txt";
var File2 = Dts.Variables["User::FTPWORKINGDIR"].Value.ToString() + "\\SSIS_PSFTP_REN_script.txt";
lineOut = "del " + Dts.Variables["User::ARCHIVEFILE"].Value.ToString() + Environment.NewLine + "bye";
System.IO.File.WriteAllText(File1, lineOut);
lineOut = "ren " + Dts.Variables["User::FTPFILE"].Value.ToString() + " " + Dts.Variables["User::ARCHIVEFILE"].Value.ToString() + Environment.NewLine + "bye";
System.IO.File.WriteAllText(File2, lineOut);
Dts.TaskResult = (int)ScriptResults.Success;
}
Researching it doesn't really give anything helpful, and kind of just leads me back to where I am right now.
Try using a foreach loop on files for each file that can be processed and put all the processing of the file inside it. And do not put any precendence constraints between the foreach loops.
This will process the files that are there an not fail when the others aren't there.
The foreach loop essentially works as a check if the file exists.
This assumes you do not need all the files to properly process them.
Why not checking if the file exists before writing the script:
if (System.IO.File.Exists(Dts.Variables["User::ARCHIVEFILE"].Value.ToString())){
lineOut = "del " + Dts.Variables["User::ARCHIVEFILE"].Value.ToString() + Environment.NewLine + "bye";
System.IO.File.WriteAllText(File1, lineOut);
}
if (Dts.Variables["User::FTPFILE"].Value.ToString())){
lineOut = "ren " + Dts.Variables["User::FTPFILE"].Value.ToString() + " " + Dts.Variables["User::ARCHIVEFILE"].Value.ToString() + Environment.NewLine + "bye";
System.IO.File.WriteAllText(File2, lineOut);
}
C#, Winforms:
I have a log file I need to parse. This file contains transactions requests from a program, but the program writes the transaction across multiple lines.
I need to get the ID# and if the request was processed or denied for whatever reason. The problem is that these requests are on multiple lines. My only saving grace is that they contain the same time stamp from the logger. The (##) is not usable since it is a temporary placeholder, thus (19) may repeat multiple times throughout the log.
I was thinking of scanning for a PR_Request, substringing the ID# and the time stamp, but I dont know how to make a streamreader move down to the next 4 lines and write it out to be one single line in a file.
Examples:
06/10/16 08:09:33.031 (1) PR_Request: IID=caa23b14,
06/10/16 08:09:33.031 (1) PR_Mon: IID=caa23b14,
06/10/16 08:09:33.031 (1) RESUME|BEGIN
06/10/16 08:09:33.031 (1) RESUME_TRIG|SC-TI
06/10/16 08:19:04.384 (19) PR_Request: IID=90dg01b,
06/10/16 08:19:04.384 (19) PR_Mon: IID=90dg01b,
06/10/16 08:19:04.384 (19) RESUME|DENIED: Access not granted.
I need output to be in a single line for a file. That way, I can just parse it with another program and feed the data into a database.
06/10/16 08:09:33.031 PR_Request: IID=caa23b14 | RESUME | BEGIN | RESUME_TRIG | SC-TI
06/10/16 08:19:04.384 PR_Request: IID=90dg01b | RESUME | DENIED: Access not granted.
EDIT:
Okay I think I have a base code here. It works, kind of. It takes such a long time because I had to open another file streamer when it found a match to PR_Request, then scan the file again with the same fullstamp (date + process number). It will then look for RESUME|BEGIN or RESUME|DENIED and then write out that it succeeded or failed.
Is there any way to perhaps speed this up by getting the streamreader line where it originally found the PR_Request, have it start on another line, count maybe to 5 more lines, then stop it? This would help speed up the program considerably.
string inputfolder = inputloctxt.Text;
string outputfolder = saveloctxt.Text;
string outputfile = #"ParsedFile.txt";
try
{
string[] readfromdir = Directory.GetFiles(outputfolder);
foreach (string readnow in readfromdir)
{
using (StreamReader fileread = new StreamReader(readnow))
{
string fileisreading;
while ((fileisreading = fileread.ReadLine()) != null)
{
if (fileisreading.Contains("PR_Request"))
{
string resumed = null;
string fullstamp = fileisreading.Substring(1, 26);
string datestamp = fileisreading.Substring(1, 21);
string requesttype = fileisreading.Substring(27, 22);
string iidnum = fileisreading.Substring(53, 8);
using (StreamReader grabnext01 = new StreamReader(readnow))
{
string grabnow01;
while ((grabnow01 = grabnext01.ReadLine()) != null)
{
if (grabnow01.Contains(fullstamp))
{
if (grabnow01.Contains("RESUME|BEGIN"))
{
resumed = "TRUE";
break;
}
else if (grabnow01.Contains("RESUME|DENIED"))
{
resumed = "FALSE";
break;
}
}
}
}
File.AppendAllText(outputfolder + outputfile,
datestamp + " " + requesttype + " " + iidnum + " " + resumed + Environment.NewLine);
resumed = null;
}
}
}
}
}
This sounds like you need to use Regular Expressions. There is a namespace System.Text.RegularExpressions you can use and reference the capture groups that I made for you in the example.
Use these sites for reference:
https://regex101.com/
https://msdn.microsoft.com/en-us/library/bs2twtah(v=vs.110).aspx
I started off the Regex for you, it is not pretty but it should get the job done.
(?:\d{2}\/\d{2}\/\d{2}\s\d{2}\:\d{2}\:\d{2}\.\d{3}\s\(\d+\)\s)(PR_Request: IID=[^,\n]+)(?:\,\n\d{2}\/\d{2}\/\d{2}\s\d{2}\:\d{2}\:\d{2}\.\d{3}\s\(\d+\)\sPR_Mon: IID=[^,\n]*\,\n\d{2}\/\d{2}\/\d{2}\s\d{2}\:\d{2}\:\d{2}\.\d{3}\s\(\d+\)\s)((RESUME|BEGIN|\||DENIED: Access not granted.)*)(?:\n\d{2}\/\d{2}\/\d{2}\s\d{2}\:\d{2}\:\d{2}\.\d{3}\s\(\d+\)\s)*((RESUME_TRIG|SC\-TI|\|)*)
I have a program that is a launcher for a mod for a game. The launcher works for most of the people who use it, including myself, but for some there is a strange bug that really has me struggling to fix it, and further more driving me absolutely mental!
The basic idea is that my mod files are contained in a folder, the launcher iterates through these files, reads a certain byte of the file and based on the result either moves the file, or moves the file and writes some text to a certain file, then launches the game. Seemingly simple.
The main launch function looks like this:
private void Launch()
{
using (StreamWriter writer = new StreamWriter(userScriptPath, false, Encoding.Unicode))
{
foreach (string file in Directory.GetFiles(modFolderPath + "\\Files\\", "*.pack"))
{
int p = GetPackType(file);
if (p == 3)
{
if (File.Exists(modFolderPath + "\\Files\\" + Path.GetFileName(file)))
{
File.Move(modFolderPath + "\\Files\\" + Path.GetFileName(file), dataPath + "\\" + Path.GetFileName(file));
}
writer.WriteLine("mod \"" + Path.GetFileName(file) + "\";");
}
else if (p == 4)
{
if (File.Exists(modFolderPath + "\\Files\\" + Path.GetFileName(file)))
{
File.Move(modFolderPath + "\\Files\\" + Path.GetFileName(file), dataPath + "\\" + Path.GetFileName(file));
}
}
}
}
Process game = Process.Start(gamePath);
// There is code here that waits for a minute until the game process is actually found, incase its slow starting up
game.WaitForExit();
RestorePacks(); // <- Method to put back the files after finishing
}
The problem some users are getting is that when launching the mod the game launches but it appears as though the launcher doesn't move the files as the game is still in its normal state, it was very hard to ascertain exactly why this was happening as I had no way of debugging it on their computers and the program was working fine for me and all of my test users.
To try and find out what was going on I added a number of checks and some logging to the launcher so that if the launcher didn't work, I'd at least have an idea why. (Note that no errors are thrown for the users even when it doesn't work)
The checks I added included using File.Exists() after attempting to move a file to make sure it was actually moved, the logging kept a note of move attempts and the result of this check to see if the file was actually moved.
I even added a specific if statement to the Process.Start function checking specifically that a certain file was indeed in the required location before launching the game.
Finally before launching all of the files in the folder where the mod files should now be are written to the log.
All of the logs from users who the launcher didn't work for shared one thing in common the program attempted to move the file, threw no error, and then when checking that the file was indeed moved, the file appeared to be there. But when reaching the point where all of the files in the required directory are written to the log, only one of the required 30+ mod files appear to be in the directory.
An example output log looked something like this:
File moving: modfile1.txt
Checking if file is where we tried to move it to: Yes
File moving: modfile2.txt
Checking if file is where we tried to move it to: Yes
File moving: modfile3.txt
Checking if file is where we tried to move it to: Yes
Writing out all files in directory:
normalgamefile1.txt
normalgamefile2.txt
normalgamefile3.txt
modfile1.txt
After seeing this and noticing it was always only a single file that had moved and no others, and also that the program did think the files were where they where supposed to be, the confusion really started to kick in.
This is the method that reads the file to ascertain what type of file it is:
private int GetPackType(string path)
{
FileStream fs = File.OpenRead(path);
BinaryReader reader = new BinaryReader(fs);
reader.ReadChars(4);
int packType = reader.ReadInt32();
fs.Close();
fs.Dispose();
return packType;
}
As you can probably see, and what I've just noticed is that I've failed to close/dispose of reader, and I'm guessing and somewhat hoping this might be the cause of my problem.
(Note I'm now using Using statements in this method but can't test this fix for quite a while)
SO, if you've read this far thank you, my question is..
Firstly do you have any idea what the problem is? Could it be that reader still might have the file open and has not closed and thus the file can't move, IF SO then why does it work perfectly for me and most others, but not for some? Surely a file still being used elsewhere would throw an error?
I've gone through all the simple stuff like making sure the program is run with administrator privileges, etc.
Thank you greatly for any help!
EDIT
As asked in the comments this is the version of the code with my checks and logging added. Simple stuff, which is why I omitted it, the log simply adds to a string, the string is then printed to file when all is done.
private void Launch()
{
using (StreamWriter writer = new StreamWriter(userScriptPath, false, Encoding.Unicode))
{
foreach (string file in Directory.GetFiles(modFolderPath + "\\Files\\", "*.pack"))
{
int p = GetPackType(file);
if (p == 3)
{
if (File.Exists(modFolderPath + "\\Files\\" + Path.GetFileName(file)))
{
File.Move(modFolderPath + "\\Files\\" + Path.GetFileName(file), dataPath + "\\" + Path.GetFileName(file));
}
log += "Move File: " + Path.GetFileName(file) + "\r\n";
writer.WriteLine("mod \"" + Path.GetFileName(file) + "\";");
log += "Write mod line: " + Path.GetFileName(file) + "\r\n";
}
else if (p == 4)
{
if (File.Exists(modFolderPath + "\\Files\\" + Path.GetFileName(file)))
{
File.Move(modFolderPath + "\\Files\\" + Path.GetFileName(file), dataPath + "\\" + Path.GetFileName(file));
}
log += "Move File: " + Path.GetFileName(file) + "\r\n";
}
// Check the file did actually move
if (File.Exists(dataPath + "\\" + Path.GetFileName(file)) == false)
{
MessageBox.Show("The mod could not launch successfully!\n\nError: Packs failed to move", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
log += "File Found\r\n";
}
}
}
if (File.Exists(dataPath + "\\_GreatWar5_DB.pack")) // This pack should always be there if things have worked
{
Process game = Process.Start(gamePath);
}
else
{
MessageBox.Show("The mod could not launch successfully!\n\nError: Data pack missing", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// There is code here waits for a minute until the game process is actually found, incase its slow starting up
game.WaitForExit();
RestorePacks(); // <- Method to put back the files after finishing
}
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.