C# argument " instead of backslash - c#

my code is
a.exe
string programName = AppDomain.CurrentDomain.FriendlyName;
ProcessStartInfo proc = new ProcessStartInfo();
proc.FileName = "b.exe"
proc.Arguments = programName + " \"" + AppDomain.CurrentDomain.BaseDirectory + "\"";
Process.Start(proc)
and check the value another program
b.exe
MessageBox.Show(args[0]);
MessageBox.Show(args[1]);
i predict value is
args[0] = a.exe
args[1] = D:\my test\with space\Folder\
but the value is
args[0] = a.exe
args[1] = D:\my test\with space\Folder"
QUESTION
BaseDirectory : C:\my test\with space\Folder\
so i cover BaseDirectory with " because has space.
as a result i want
b.exe a.exe "C:\my test\with space\Folder\"
but at b.exe check args[1] value is
D:\my test\with space\Folder"
where is my backslash and why appear "
help me please...

As Kayndarr already pointed out correctly in the comments, you are escaping " in your path.
There are certain characters which the compiler will not interpret as part of the string, due to their special meaning.
In order to let the compiler know, you want those characters interpreted as part of the string instead, you have to write them in a so called "escape-sequence".
I.e. that means putting a backslash in front of them.
Since the backslash itself has therefor also a special meaning as escape-character - you have to escape the slash, if you want it to be interpreted as part of the string.
"\\"
Will generate a literal string with one backslash in it, since the first backslash is used to escape the second.
The fix in your example would therefor look as follows:
string programName = AppDomain.CurrentDomain.FriendlyName;
ProcessStartInfo proc = new ProcessStartInfo();
proc.FileName = "b.exe"
proc.Arguments = programName + "\\" + AppDomain.CurrentDomain.BaseDirectory + "\\";
Process.Start(proc);

Related

How do I use an illegal character?

public void CreateCertificate()
{
File.Create($"
{#"C:\Users\Director\Documents\TestCertApp\TestSub\" + thisYear +
" Certificates- " + certType + "\""}{myFileName}.ppt", 1 ,
FileOptions.None);
}
So I need the backslash between certype and filename to show it belongs within the folder and not next to. It says its an illegal character but how would I get the file in the folder without it?
Based on the code that you wrote the file path that will be generated is (based on my own substitutions for the variables):
String thisYear = "2019";
String certType = "UnderGrad";
String myFileName = "myfile";
String fileToCreate = $"{#"C:\Users\Director\Documents\TestCertApp\TestSub\" + thisYear + " Certificates- " + certType + "\""}{myFileName}.ppt";
Debug.Print(fileToCreate);
Will give you this output:
C:\Users\Director\Documents\TestCertApp\TestSub\2019 Certificates- UnderGrad"myfile.ppt
If you notice there is a " before the filename part of myfile.ppt - This is where the Illegal Character comes from.
If you use this code fragment to generate the path:
String basePath = #"C:\Users\Director\Documents\TestCertApp\TestSub\";
String certificateFolder = $"{thisYear} Certificates- {certType}";
String correctFilePath = Path.Combine(basePath, certificateFolder, $"{myFileName}.ppt");
Debug.Print(correctFilePath);
This will result in the output of:
C:\Users\Director\Documents\TestCertApp\TestSub\2019 Certificates- UnderGrad\myfile.ppt
This version has a \ where the previous code had a " and is no longer illegal, but conforms to the requirement that you wrote the files being in the folder.
Something else to note:
You may want to use Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); to get the path to the MyDocuments folder of the user.
Well, the short answer is that you cannot use an illegal character in a path or file name. Otherwise it wouldn't be illegal. :)
But it seems that the problem here is that you though you were adding a backslash (\) character, when really you were adding a double quote (") character. So if everything else is ok, you can just replace "\"" with "\\" and it should work.
Part of the problem is also that you're doing some strange combination of string interpolation, and it makes the code really hard to read.
Instead you can use just string interpolation to simplify your string (I had to use concatenation below to prevent horizontal scrolling, but you could remove it):
string filePath = $#"C:\Users\Director\Documents\TestCertApp\TestSub\{thisYear} " +
$#"Certificates- {certType}\{myFileName}.ppt";
But even better would be to use the Path.Combine method, along with some variables, to make the intent very clear:
var rootDir = #"C:\Users\Director\Documents\TestCertApp\TestSub"
var fileDir = $"{thisYear} Certificates- {certType}"
var fileName = "{myFileName}.ppt";
var filePath = Path.Combine(rootDir, fileDir, fileName);

Having trouble while adding double quotes to a string that is inside a variable in C#?

I am trying to pass a filepath to xcopy command for copying a folder from one location to another( CodedUI using C#).
While doing the same the problems is, I am trying to add double quotes around the path but it's not taking the correct path format.
Code:
string Path = "Some path to folder location";
// Tried all these solutions
Path = '\"' + Path + '\"';
Path = '\"' + Path + '\"';
Path = string.Format("\"{0}\"", Path );
Expected: ""Some path to folder location""
Actual:"\"Some path to folder location"\"
Please help.
In debugger you will see the backslash.
Sent your output to Console and you will see the result is good.
string Path = "Some path to folder location";
Path = "\"" + Path + "\"";
Console.WriteLine(Path);
From what i understand, you want to see
"Some path to folder location"
when you print it. If so, do:
string path = "\"Some path to folder location\"";
or
string path = "Some path to folder location";
var finalString = string.Format("\"{0}\"", path);
Maybe you should try verbatim strings like #"the\path\to\another\location".
This is the best way to write paths without having to struggle with escape codes.
EDIT:
You can use double quotes in a verbatim string:
#"""the\path\to\another\location"""
If you're trying to preserve two sets of double quotes, try building the string like so:
var path = "hello";
var doubleQuotes = "\"\"";
var sb = new StringBuilder(doubleQuotes)
.Append(path)
.Append(doubleQuotes);
Console.WriteLine(sb.ToString()); // ""hello""
Of course, if you want single quotes you simply swap doubleQuotes for singleQuotes = "\""; and get "hello".
To add double quote, you need to add '\' before ' " '.
Note that : if you are having '\' in path, you have to take care of it like below.
if path is "D:\AmitFolder"
string path = #"D:\AmitFolder";
//Or
path = "D:\\AmitFolder"
string str = "\"" + path + "\"";
Console.WriteLine(str);
here str will be "Some path to folder location"
Output:
as in above line we are adding "\"" string as prefix and "\"" as post fix of the main string.
While storing string values if any double quotes are to be added they need to be escaped using backshlash(\). Single quotes are used for character data. The following code should get the output needed.
Path = string.Format("\"{0}\"", Path);
Also I have created a small fiddle here.

C# double quote argument

In the app.config file, I have:
add key="DataFileLocation" value="E:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\"/>
In the code I have:
Process P2 = new Process();
P2.StartInfo.FileName = "restore.bat";
P2.StartInfo.Arguments = + "\"" + DataFileLocation.ToString() + "\"";
P2.StartInfo.UseShellExecute = false;
P2.StartInfo.RedirectStandardOutput = true;
P2.StartInfo.CreateNoWindow = true;
P2.Start();
The output to 'restore.bat' is:
-v dataloc=\"E:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\\"
As you can see, there's an extra "\" at the beginning which is breaking the bat/sql statement...
Andrew
In your case it seems like you are already adding a extra \, so is the output according to your logic.
The best way to combine path is that you should use the Path.Combine method provided by static Path class, it takes care of all the extra \
Try this
var finalPath = Path.Combine(DataFileLocation.ToString(), "what_ever_path_you_want_to_combine");

Arguments are not passing into command prompt

string appPath = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));
Process p = new Process();
p.StartInfo = new ProcessStartInfo("cmd.exe", #"/c opencvproject.exe " + #appPath + #"\\bin\\Debug\\center\\centerilluminate.jpg");
p.Start();
I tried this at my other computer and it works , however when I tried it in my new computer this doesn't work somehow. Anyone knows how to solve this? The program I am using is c# and im calling cmd to call c++ program which is opencvproject.exe
There are still multiple instances where I use cmd to trigger other c++ program and python scripts to run and those are not working too. I am not sure what am I doing wrong..
Hold the path between double quotation.
p.StartInfo = new ProcessStartInfo("cmd.exe", "/c opencvproject.exe \"" + appPath + "\\bin\\Debug\\center\\centerilluminate.jpg\"");
Explanation
Character combinations consisting of a backslash () followed by a letter or by a combination of digits are called "escape sequences."
http://msdn.microsoft.com/ja-jp/library/h21280bw.aspx
# makes escape sequence no effect, so..
var s1 = #"\\bin\\Debug\\"; // This contains wrong path \\bin\\Debug\\
var s2 = "\\bin\\Debug\\"; // This contains right path \bin\Debug\
And need using escape sequence to hold the double quotation between double quotation.
var s3 = "\"\\bin\\Debug\\\""; // This contains "\bin\Debug\"
var s4 = #"\"\\bin\\Debug\\\""; // compile error
The # character automatically escapes characters in the string behind it, so you shouldn't double backslash your path.
Eg, where you have:
#"\\bin\\debug\\.."
it should either be:
#"\bin\debug\..."
or:
"\\bin\\debug\\.." (without the #)
Also, if your apppath contains spaces, then you should surround the entire string with " characters

How to specify parameters with spaces when starting a new process

i would like to run a process with the parameter: filename.
string parms = filechooser.Filename ;
psi = new ProcessStartInfo("timidity", parms);
The problem occur when user choose a filename with some spaces.
Ho can i pass the parameter with the " " ?
Thanks
You could wrap the value in double quotes:
string parameters = string.Format("\"{0}\"", filechooser.Filename);
psi = new ProcessStartInfo("timidity", parameters);
That should work just fine, the spaces will be passed too.
However if you want to escape the filename (which depends on the app being started, i.e. timidity), do this:
string parms = string.Format("\"{0}\"", filechooser.Filename);
psi = new ProcessStartInfo("timidity", parms);
This will create a string based on the format \"{0}\". \" becomes a quote (") and {0} will be replaced with the first parameter after the format string, i.e. the filename.
You can try this out using the Start, Run feature or command prompt (cmd.exe). Enter timidity then your full filename, with spaces, in quotes and see if that works:
timidity "my filename"
Try this.
string parms = filechooser.Filename ;
psi = new ProcessStartInfo("timidity", "\"" + parms + "\"");
Backslash is your friend:
"\"timidity\""

Categories

Resources