Create and run a batch file containing special chars as accent - c#

I am actualy creating a batch file from my C# application. (path contains accents for example)
using (System.IO.StreamWriter file = new System.IO.StreamWriter("file.bat", false))
{
var path = "C:\directory_été";
var whoot = #"#echo off" + Environment.NewLine + #"pushd %~dp0" + Environment.NewLine + path; // where path contains accents and such
file.Write(whoot);
}
When opening the .bat file with notepad.exe, everything looks written perfectly.
Then my app is running the batch.
var Info = new ProcessStartInfo();
Info.Arguments = "/C choice /C Y /N /D Y /T 3 & start /b \"myBatchTitle\" \"C:\\file.bat\"";
Info.WindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "cmd.exe";
Process.Start(Info);
The batch returns an error because it is not finding the "path" because it changed the accents into some garbage characters.
So, everything looks ok in the .bat itself, but when running it, it fails reading correctly cause of the encoding.(path echoed as "directory_ÚtÚ" when batch is ran, i cant even copy the Ú from cmd prompt cause its printed correctly here then lol)
How can i fix this please? (and not MANUALLY change characters one by one)
Or isn't there a way to encode the string in C# to OEM something so it will be reading correctly? (example change é to Ú already, for ALL characters)
(For more infos, the created batch file is running 7zip command line version, and the path i submit to it is containing the accents and such)
Otherway, do you know any portable-command-line alternative, accepting real UTF8 encoding so ll languages will be accepted?

I don't know what the appropriate code page is for C:\directory_été (maybe you do, since you are dealing with this file). You can try codepage 863, which is for Canadian French.
In any case, if you know the codepage, you could try changing code page via chchp xxx where xxx is the number identifying the code page you want to switch to. So you could try chcp 863. You can put this in your batch file before you use the path with the accents.

Related

cant send specific command with StreamWriter but when enter command manually its working

I built a program that dump memory and i'm using an open source tool called "dumpty" to make strings of the dumped memory
"dumpty" tool github
when I open a command line use the tool and write those four commands:
cd dumpty_folder_root
dumpty -e repl
load "dumped file name.dmp"
dumpstrings strings
it works fine and I get new folder with the strings
but when I send the command via StreamWriter it isn't working here you can see the code I use:
dumptyProcess.StartInfo.UseShellExecute = false;
dumptyProcess.StartInfo.RedirectStandardInput = true;
dumptyProcess.StartInfo.RedirectStandardOutput = true;
dumptyProcess.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");
dumptyProcess.StartInfo.CreateNoWindow = true;
dumptyProcess.Start();
//Encoding encoding = Encoding.Default;
StreamWriter wr = dumptyProcess.StandardInput;
string str = "load \""+dumpFilePath;
//StreamWriter wr = new StreamWriter(dumptyProcess.StandardInput.BaseStream, encoding);
wr.WriteLine("cd " + Directory.GetCurrentDirectory());
wr.WriteLine("dumpty -e repl");
wr.WriteLine(str);
wr.WriteLine("dumpstrings strings");
wr.Flush();
richTextBox_info.Text += "Running strings on dump file...\n";
I know that when I use StreamWriter all command working except the third command that load the dump file but i don't know why (again if i do it manually it works) i know all command are working because it creates the strings folder but no strings inside
things i tried:
1. changing the dump file name without spaces and change the command without quotes
2. try changing the encoding of the dumptyProcess
3. copy every command that I enter when using manually cmd to see if they work (they did)
for some reason I cant load the dump file please help

forcing to close a file

I have file that another process using it.
and I want to force closing the file. so that I will work on the fill.
I tried to use Handle.exe however it didn't find the process
would appreiciate some help here is my code:
Process tool = new Process();
tool.StartInfo.FileName = handlPath;
tool.StartInfo.Arguments = _pathDirectory + " /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();
string matchPattern = #"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach (Match match in Regex.Matches(outputTool, matchPattern))
{
Process.GetProcessById(int.Parse(match.Value)).Kill();
}
I'm sure, that if a program really holds an exclusive access to a file, it has a reason to do it. For example, Windows Explorer holds it when the file is in copying process.
Very often, programs open a file for a writing, but do not actively write to it. For example, when you open a document in MS Word, it is copied to the temp file and a source file is just "open for writing". You'll still have an exception if you use standard File.Open method, but you can copy it to a temp file using File.Copy.
Alternatively, you can explicitly specify FileShare.ReadWrite parameter and get an access to a file. In this case, other program will have problems with accessing a file.
If you have mentioned the file name or type it would have been more easier, anyway try using the cmd for this. Get the process name and replace ProcessName.exe of the following code.
First you'll have to add using System.Diagnostics; on top.
Process.Start("cmd.exe", "/c taskkill /F /IM ProcessName.exe");

Unzip files in C# (using winzip command line)

I'm trying to create program to unzip files. I need to use winzip command line. I try to send in argument command to cmd, but it didn't work, because cmd didn't know my command. When I pasted manually command, it works.
var process = new ProcessStartInfo("cmd.exe");
var command = "/c WZUNZIP -spassword" + "\""+ "C:\my path\file.zip" + "\"" + " " + "\"" + "C:\my path" + "\"";
process.UseShellExecute = false;
process.Arguments = command;
Process.Start(process);
I tried to create .bat file and execute this file in my program, but like before it didn't work, when I executed it in my program and when start manually it works.
start cmd.exe /c WZUNZIP -spassword "C:\my path\file.zip" "C:\my path"
var process = new ProcessStartInfo("cmd.exe", pathToBatch);
Process.Start(process);
Mayby u know, the best way to execute .bat file in C#.
I need to use winzip, because only it provides encoding for my files. I tried to use DotNetZip and during uziping program threw exception that it can't be unziped, because library can't operate this files.
Apologies for adding as an answer (I currrently don't have enough rep for posting comments), but hopefully this will help.
What is the reason that you need to use winzip command line? Could you use ionic zip instead (http://dotnetzip.codeplex.com/ - also obtainable via NuGet in Visual Studio). I've used it a few times to zip files up and I know it unzips just as well.
The benefit I can see of not using the winzip command line is that you don't get the command prompt window popping up onscreen while the unzip is in progress.
Otherwise, as Noodles has suggested, the quotes must go around the whole path, not just the folders containing the spaces.
Edit: There is a similar SO post here: unzip file in C# via Winzip and its cmd extension
If you want to execute any thing you can use the process class with ProcessStartInfo.Arguments.
You can see more at:
MSDN: Process Class
MSDN: ProccessStartInfo.Arguments Property
And my question is because I don't understand for what you want it,
why don't you use system.IO.Compression or SharpzipLib? You can look up more info and download it with nugget.
Quotes go aroundthe entire path incl drive letter "c:\some folder\some file.zip"
To unzip
Set objShell = CreateObject("Shell.Application")
Set Ag=Wscript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set DestFldr=objShell.NameSpace(Ag(1))
Set SrcFldr=objShell.NameSpace(Ag(0))
Set FldrItems=SrcFldr.Items
DestFldr.CopyHere FldrItems, &H214
Msgbox "Finished"
and to zip
Set objShell = CreateObject("Shell.Application")
Set Ag=Wscript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set SrcFldr=objShell.NameSpace(Ag(1))
Set DestFldr=objShell.NameSpace(Ag(0))
Set FldrItems=SrcFldr.Items
DestFldr.CopyHere FldrItems, &H214
Msgbox "Finished"
and create a blank zip.
Set Ag=Wscript.Arguments
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(Ag(0), 8, vbtrue)
BlankZip = "PK" & Chr(5) & Chr(6)
For x = 0 to 17
BlankZip = BlankZip & Chr(0)
Next
ts.Write BlankZip
Here's what works for me:
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", #"/c WZUNZIP.EXE -ye -o " + zipPath + " " + ExtractedFilesLocation);
procStartInfo.UseShellExecute = false;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();

How to avoid that a string splits on every whitespace in command line

I'm writing a program in which the user can type in some informations about a customer and then open a MS Word model (*.dotx). After that he can directly archive it with another program. So I click on a button which I created for MS Word and then it should open the other program (the archive program) and pass the path to the *.dotx file to it. I got this code to pass the path and open the archive program:
Process p = new Process();
p.StartInfo.Arguments = "Word " + secondArgument;
p.StartInfo.FileName = fileName;
p.Start();
The string secondArgument ist the path to the file and fileName is the path to the exe file of the archive program.
To get the arguments in the archive program, I use this code in Form_Load():
string[] args = Environment.GetCommandLineArgs();
Then I use a MsgBox to look if it's correctly passed. But it isn't. The name of the .dotx file has whitespaces in it (e.g. "path\This is a test file.dotx"). So the output of MessageBox.Show(args[0]) is "path\This". How can I avoid that it splits at every whitespace?
Suggestions appreciated :)
You need to surround it with quotation marks:
"This is a test file.dotx"
MSDN:
Command line arguments are delimited by spaces. You can use double
quotation marks (") to include spaces within an argument.

running batch file, getting error and process output into a text file

hi for the following code, why is it that i am getting this output in the error text file?
"'ha57061' is not recognized as an internal or external command,
operable program or batch file."
my user name is cha57061. why am i missing the "c" and " ' "? please correct me if my code is wrong.
System.Diagnostics.Process runantc = new System.Diagnostics.Process();
runantc.StartInfo.FileName = "C:/Documents and Settings/Cha57061/Desktop/New Folder/WPF/WpfApplication1/WpfApplication1/cmd.exe";
runantc.StartInfo.Arguments = "antc.bat";
runantc.StartInfo.UseShellExecute = false;
runantc.StartInfo.RedirectStandardOutput = true;
runantc.StartInfo.RedirectStandardError = true;
runantc.Start();
string procOutput = runantc.StandardOutput.ReadToEnd();
string procError = runantc.StandardError.ReadToEnd();
TextWriter outputlog = new StreamWriter("C:/Documents and Settings/Cha57061/Desktop/New Folder/WPF/WpfApplication1/WpfApplication1/processoutput.txt");
outputlog.Write(procOutput);
outputlog.Close();
TextWriter outputerror = new StreamWriter("C:/Documents and Settings/Cha57061/Desktop/New Folder/WPF/WpfApplication1/WpfApplication1/error.txt");
outputerror.Write(procError);
outputerror.Close();
Not sure if it solves your problem, but this is the first time i'm seeing file paths in C#.NET using forward slashes (/), not sure if they get converted to (\) automatically.
You might try rewriting your paths as indicated below
"C:\\Directory\\File" //the double slash is necessary since (\) indicates an escape character is to come)
#"C:\Directory\" // the # modifier changes the default behavior and escape characters are not considered the same way
\c is a escape character, as described here: http://msdn.microsoft.com/en-us/library/4edbef7e%28v=vs.71%29.aspx
That's the wrong way to run a batch file.
You should set FileName directly to the path to your .bat file.
To answer your question, your batch file has a problem.

Categories