how to give address of parts to copy command in c# - c#

when i run copy command in my c# code it produce no error or exception because it is not finding the parts path i do not know how to give full directory path or path of every part which i am joining.actually i am merging file parts to a single file using coy/b by using this code...
string strCmdText;
strCmdText = "/C copy/b test.txt.10485760.0000.part" +
"test.txt.10485760.0001.part" +
"test.txt.10485760.0002.part" +
"test.txt.10485760.0003.part" +
"test.txt.10485760.0004.part" +
"test.txt.10485760.0005.part test.txt";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);

You can specify the path of your files as the working path of the process. For example:
var startInfo = new System.Diagnostics.ProcessStartInfo
{
WorkingDirectory = #"THE\PATH\OF\FILES",
WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal,
FileName = "cmd.exe",
Arguments = "YOUR COMAND HERE";
};
Process process = Process.Start(startInfo);
For your command, note that you can copy all files into one using a wildcard for the parts:
copy *.part test.txt
/b is for binary data, so i think is not needed in your case.
You can also set other properties for a process, for more info check the doc: ProcessStartInfo.

For such a complex task, I would use the process as a bash rather then just an execution tool.
Create a Process
Redirect it's streams (Input, Output)
With a StreamReader and StreamWriter u can now access the cmd
Now just control it the way u need it, like setting the working directory to the path and do ur command.
If this is not what u want, u can allways set the working directory on the ProcessStartInfor -> Link

Related

How do i include batch files inside of my .exe Instead of needing them in the folder the .exe is located in

So been searching or the web but can't seem to find an answer that has helped me. I have been looking for almost a week now.
I created a program in vs, alongside with some batch files. The Batch files run great by themselves and through the debug/release when including them in the folder with the .exe.
My problem is I want to be able to ONLY have the .exe file from my release and it still work.
Is there a way i can build these files inside the .exe? I have tried using c# to write my console commands instead of including seperate batch files. But im pretty new to c# and i get nothing but errors with the commands i want to run/if i run to many lines.
I would much rather have just c# instead of including the batch files but that I can't seem to figure out a solution to either.
Any help would be appreciated.
This is me currently calling batch files which works just fine. Again, if there is a way to just write this in c# instead of calling a batch file I would be happy to learn.
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.CreateNoWindow = false;
psi.Verb = "runas";
psi.FileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"/" + "undo.bat";
psi.UseShellExecute = true;
process.StartInfo = psi;
_ = process.Start();
process.WaitForExit();
I'm starting CyberSecurity soon and am playing around with some Security stuff on my computer. Below is a sample code from my batch file to enable Security Protocols. If anything how would i write this in c#?
echo ...
echo Enabling Windows Firewall
netsh advfirewall set allprofiles state on
echo Enalbing HyperVisor
bcdedit /set hypervisorlaunchtype auto
echo Enabling UAC
%windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 1 /f
echo.
echo.
echo Your Computer will now be restarting for changes to take effect!
timeout 10
shutdown /r /t 001
What you can do is include the batchfiles as embedded resources in your project. Then read them and then execute them.
to include them as embedded resources example...
add them to your project.
right click and go to properties
select embedded resource
then to extract...
Write file from assembly resource stream to disk
you can then write the file to disk and create process on it. or there is a way to execute cmd.exe without writing the file to disk but this is a little complicated so the best way is to just write to disk.
Execute BATCH script in a programs memory
I followed the guide given above and a few others to get my solution to work. Embed the resource that's in your solution, then I used the following code to pretty much create the functions of being able to write it.
private static void Extract(string nameSpace, string outDirectory, string internalFilePath, string resourceName)
{
Assembly assembly = Assembly.GetCallingAssembly();
using (Stream s = assembly.GetManifestResourceStream(nameSpace + "." + (internalFilePath == "" ? "" : internalFilePath + ".") + resourceName))
using (BinaryReader r = new BinaryReader(s))
using (FileStream fs = new FileStream(outDirectory + "//" + resourceName, FileMode.OpenOrCreate))
using (BinaryWriter w = new BinaryWriter(fs))
w.Write(r.ReadBytes((int)s.Length));
}
Here is what I used to save, execute then delete the file.
Extract("nameSpace", "outDirectory", "internalFilePath", "resourceName");
Process process = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.CreateNoWindow = false;
psi.Verb = "runas";
psi.FileName = #"C:/" + "resourceName";
psi.UseShellExecute = true;
process.StartInfo = psi;
_ = process.Start();
process.WaitForExit();
System.Threading.Thread.Sleep(10);
if ((System.IO.File.Exists(psi.FileName)))
{
System.IO.File.Delete(psi.FileName);
}
Keep in mind im new when it comes to this so im sure there is a better way of writing it, but this worked for me!

How to create a text file using cmd in c#?

I wanted to create a text file with all names of the files in a folder.
So I went like this:
Process getNamesProcess = new Process();
getNamesProcess.StartInfo.FileName = #"c:\**my folder path**";
getNamesProcess.StartInfo.Arguments = "dir /b >> names.txt";
getNamesProcess.Start();
However this doesn't work for me. The process opens me a folder, nothing more. What should I change?
I do not know what you were hoping to accomplish by placing a folder path in StartInfo.FileName, but what you need to put in there is the full path to cmd.exe.
Then, in StartInfo.Arguments you need to put "/C dir /b " + my_folder_path + " >> names.txt".
For an explanation of what the /C does, open up a command prompt and type help cmd.
A better way would be:
File.WriteAllLines("names.txt", Directory.GetFiles("c:\\path").Select(Path.GetFileName));
The File, Directory and Path classes are in the System.IO namespace.

How to pass parameters to an exe?

I am using psexec on my server to run an exe file on another server. How do I pass parameters to the other exe ?
The exe that I am running on my server is psexec which in turn must run the exe named vmtoolsd.exe located on another system. How do I pass parameters to vmtoolsd.exe ? Also, where do I pass it ? Would I pass it as part of the info.Arguments ? I've tried that but it isn't working.
ProcessStartInfo info = new ProcessStartInfo(#"C:\Tools");
info.FileName = #"C:\Tools\psexec.exe";
info.Arguments = #"\\" + serverIP + #"C:\Program Files\VMware\VMwareTools\vmtoolsd.exe";
Process.Start(info);
Also, as part of info.Arguments would I have to preface the path of vmtoolsd.exe with the IP address, followed by the drive path ?
Hope the below code may help.
Code from first .exe:
Process p= new Process();
p.StartInfo.FileName = "demo.exe";
p.StartInfo.Arguments = "param1 param2";
p.Start();
p.WaitForExit();
or
Process.Start("demo.exe", "param1 param2");
Code in demo.exe:
static void Main (string [] args)
{
Console.WriteLine(args[0]);
Console.WriteLine(args[1]);
}
Right click on .exe file-->goto shortcut-->in target tab write the arguement in extreme right...
in my case it worked
You can see it in the following post (answer by #AndyMcCluggage):
How do I start a process from C#?
using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "process.exe";
process.StartInfo.Arguments = "-n";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
process.WaitForExit();// Waits here for the process to exit.
It provides far more control as you can see in the MSDN, but basically the arguments control is quite easy as you can see, is just to modify a property with a string.
Update: Since with the snippet code above you would be starting PsExec, based on:
PsExec
The format you have to use is:
psexec #run_file [options] command [arguments]
Where: arguments Arguments to pass (file paths must be absolute paths on the target system).
Since the process you're starting is psexec, in the process.StartInfo.Arguments you would have to put all the parameters it would need, in a sigle chain: #run_file [options] command [arguments].
Step1.Create Shortcut and then Right click on Shortcut-->click properties page then target tab write the comment line argument in extreme right... this way worked for me

C# archiving using 7zip, keeps hanging on wildcard call

Hey all quick question for you. I am trying to archive a directory of files into a zip folder using 7zip as a system process but I am running into an odd error. Whenever I do a wildcard specification in my source file name such as "*.txt" it works fine. However, once I use the wildcard * around the actual file name (Which I need to and can't work around that), 7zip just seems to hang. I can see the archive directory get created in the folder but I can't open it and I have to close 7zip down via task manager.
Any advice?
Code is below:
public static void archiveFiles(string executionDirectory,string workDirectory,
string[] files)
{
string sourceName = #"C:\mypath\*testfile*"; <----// This seems to be my issue
string targetName = #"C:\\testcompress\archive.zip";
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = #"C:\program files\7-zip\7z.exe";
p.Arguments = "a -t7z \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
}
You're most likely getting this issue because your path #"C:\mypath*testfile*" is a verbatim string, thus using the "*" character, or other such wildcards, are being taken as literal in the path instead of wildcards. Trying taking the # off the beginning of strings containing wildcards and that should fix your problem. You can find a more thorough explanation of what the "#" character, used in context of a prefix to strings, does here:
Verbatim Strings
I think you are having issues with your \'s as well as the fact that you should be using 7za.exe and not 7z.exe. Make sure your application has access to write to the directory in question.
string sourceName = #"C:\mypath\*testfile*";
string targetName = #"C:\testcompress\archive.zip";
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = #"C:\program files\7-zip\7za.exe";
p.Arguments = string.Format ( "a -t7z {0} {1} -mx=9",targetName,sourceName);
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
console.writeline(string.format("7zip returned with exit code {0}",x.ExitCode));
7zip exit codes can be found here
Remember you can test it in a command prompt window to be sure that it works.
C:\program files\7-zip\7za.exe a -t7z C:\program files\7-zip\7za.exe C:\mypath*testfile* -mx=9

Calling G++ from C# Program

I've made a C++ code editor in C# and now am trying to invoke g++ to compile the source files. So I've copied the TDM-GCC installation besides my program and wrote a small batch script to call that.
#echo off
#set PATH="%~dp0TDM-GCC-32\bin\";%PATH%
call "%~dp0TDM-GCC-32\mingwvars.bat"
cd %1
"%~dp0TDM-GCC-32\bin\g++.exe" %2 -o %3
And from C# code, I'm trying to call this script by using CMD like in this script of code.
string fileName = Path.GetFileName(CurrentFile);
string exeName = Path.GetFileNameWithoutExtension(CurrentFile) + ".exe";
string workingDir = Directory.GetParent(CurrentFile) + "";
string compile = Directory.GetParent(Application.ExecutablePath) + "\\compile.cmd";
File.Delete(Path.Combine(workingDir, exeName));
StartProcess(true, "cmd", "/c", "\"" + compile + "\"", workingDir, fileName, exeName);
And here is the StartProcess method:
void StartProcess(bool hidden, string command, params string[] args)
{
ProcessStartInfo pStartInfo = new ProcessStartInfo();
pStartInfo.FileName = command;
pStartInfo.Arguments = string.Join(" ", args);
pStartInfo.UseShellExecute = false;
if (hidden)
{
pStartInfo.RedirectStandardError = true;
pStartInfo.RedirectStandardOutput = true;
pStartInfo.CreateNoWindow = true;
}
Process proc = new Process();
proc.StartInfo = pStartInfo;
proc.Start();
logBox.Clear();
if (hidden)
{
while (!proc.StandardError.EndOfStream)
{
logBox.AppendText(GetTimestamp() + " Error: " + proc.StandardError.ReadLine() + Environment.NewLine);
}
}
}
Update: 26-9-14
I doubted whether the batch file is ever called, because if I call it from cmd, it simply works. So I tried to echo to the standard error from the batch file like this:
echo %PATH% 1>&2
And I can see that the GCC's bin folder is in the path too, but for some reason, the exe is not getting created. But sometimes, the script works, and the exe gets created.
But whenever I execute this, there will be nothing in the LOG and also, no executable is being created. I know that the TDM-GCC's bin folder must be in the PATH, but that is what the second line of the batch script needs to do. Dunno what this is and why this error.
End of update
Any suggestions on how can I get it working?
Thanks.
I don't know if anything written below really helps on this issue. But at least those hints should be useful in any case.
I suggest for the batch file
#echo off
call "%~dp0TDM-GCC-32\mingwvars.bat"
set "PATH=%~dp0TDM-GCC-32\bin;%PATH%"
cd /D %1
"%~dp0TDM-GCC-32\bin\g++.exe" %2 -o %3
PATH is modified after execution of mingwvars.bat. It could be that this batch file also modifies PATH. Or it runs commands like find.exe with the executables expected in %SystemRoot%\System32, but perhaps also existing in directory bin. I have seen already several times not working logon batch scripts because PATH on client computer contained as first folder path the bin directory of a compiler ported from Unix to Windows with executables also found in %SystemRoot%\System32, but working completely different as ported from Unix.
Folder paths should be added to environment variable PATH always without double quotes even if the folder path contains 1 or more spaces. The double quotes used in third line just make sure that a trailing space is not added additionally to PATH and that command set works even with not typical folder paths like an ampersand in path.
And folder paths should be added to environment variable PATH without a trailing backslash.
On command cd the parameter /D is additionally used in case of a change to a different drive must be performed, too. The command cd would not change the current directory if the specified path is on a different drive without parameter /D.
In C# code you have to make sure that workingDir, fileName and exeName are finally on execution of cmd.exe enclosed in double quotes in the arguments string as Erti-Chris Eelmaa already wrote.
And it would be perhaps better to read in your C# application the value of environment variable ComSpec and use this value instead of just cmd for executing the batch file.
This might, or might not be part of the problem, but you don't take care of spaces.
pStartInfo.Arguments = string.Join(" ", args);
you probably would want something like this:
pStartInfo.Arguments = string.Join(" ", args.Select(x => "\"" + x + "\""));

Categories

Resources