I have the following code:
if (BrowserName.ToUpper().Contains("FIREFOX"))
privateModeParam = " -private-window";
string extraspeech = "\"";
string both = BrowserName + extraspeech + privateModeParam;
Process.Start(both, URLFromDB);
When it run's it returns the following value:
BrowserName = "c:\\program files\\mozilla firefox\\firefox.exe"
both = "c:\\program files\\mozilla firefox\\firefox.exe\" -private-window"
privateModeParam = " -private-window"
What I need to do is, trim the \ from both string because it won't open firefox with that back slash.
I should add if I simply do:
string both = BrowserName + privateModeParam;
the value returned is "c:\program files\mozilla firefox\firefox.exe\ -private-window"
what won't open Firefox
What causes your problems is the double-quote ("), not the back-slash. There is no backslash at this position in the string, it's only displayed like that by your debugger because c# uses \ to escape things like " inside string literals.
So your problem seems to be that you forgot to add extraspeech before the executable, too:
string both = extraspeech + BrowserName + extraspeech + privateModeParam;
or better
string both = $"\"{BrowserName}\" {privateModeParam}"; // C#6
string both = string.Format("\"{0}\" {1}", BrowserName, privateModeParam); // pre C#6
Update:
But the real problem here seems to be that you pass one command line argument in the fileName parameter and one via the arguments parameter.
You should actually call Process.Start like that:
Process.Start(BrowserName, $"{privateModeParam} {URLFromDb}");
Simply pass all arguments in side the arguments parameter. Then there is also no need to wrap the executable in double-quotes as it is the only string in the fileName argument. See documentation for more information about the parameters to Process.Start().
The easiest way would be to use Substring:
MyString = MyString.Substring(0, MyString.Length - 1);
if (BrowserName.EndsWith("\\")){
BrowserName = BrowserName.Substring(0, BrowserName.Length - 1);
}
or
both = both.Replace("\\\"", "");
may fix your problem
Related
I'm trying to start a process which contains multiple spaces within the arguments. The arguments that are passed are dynamically built. For example:
// These three strings will be built dynamically
string consolePath = "C:\\My Path\\nunit3-console.exe"
string dll = "C:\\My Path\\My.Test.dll"
string where = "--where \"test == My.Test.Example \""
string cmdText = $" \"{consolePath }\" \"{dll}\" {where}";
//cmdText = "\"C:\\My Path\\nunit3-console.exe\" \"C:\\My Path\\My.Test.dll\" --where \"test == My.Test.Example \""
var processInfo = new ProcessStartInfo("cmd.exe", $"/c {cmdText}");
processInfo.CreateNoWindow = false;
Process process = Process.Start(processInfo);
process.WaitForExit();
process.Close();
This does not work as any text beyond the first space will be ignored. I will get a message such as 'C:\My' is not recognized as an internal or external command, operable program or batch file.
I tried adding parentheses around the arguments, as noted here, but it didn't work. What is the correct way to do this?
You probably have to add a further double-quote around anything that may include spaces within one single argument. Usually a space means the end of an argument. So to preserve this, you´d have to put the string into double-quotes.
So consolePath should actually be this:
var consolePath = "\"C:\\My Path....exe\"";
In addition to previous answer, # could be used to avoid \\ like this:
#"""C:\My Path\nunit3-console.exe"""
or:
"\"" + #"C:\My Path\nunit3-console.exe" + "\""
More about # here:
What's the # in front of a string in C#?
After searching two days for working string I finally found it.
Just wrap string like this:
string Arguments = "/c ""path" --argument "";
string Arguments = "/c \""path" --argument \"";
Notice bold quotes from first string.
I need to add a '\' to a string
I try this
var Filename = name.Replace("'", "\'");
name = Filename ;
if name = he's here
name.Replace("'", "\'") will return : "he\\'s here"
what I need is: he\'s here
First name.Replace("'", "\'") does nothing because "'" == "\'". So name.Replace("'", "\'") returns "he's here" (you can try it in https://dotnetfiddle.net/). What you want is: name.Replace("'", "\\'")
Second if you inspect name in the debugger (in watch window or immediate window) you will get "he\\'s here" because that is how you should write a string constant in c# to get he\'s here into a variable.
I want to ask about a easy question , but I faced a problem.
I want to get the time when the program is executed
Console.WriteLine(DateTime.Now);
And I want to output a .log file , the file name will have program execution time
String path2 = "C:\\temp"+DateTime.Now+".log";
StreamWriter path = File.CreateText(path2);
path.WriteLine(DateTime.Now);
But it is telling me Path format is illegal.
And I want ask another question
string a12 = aaa.Element("a12").tostring();
String path2 = "C:\\temp" + a12.ToString + ".log";
But it tell me "Path format is illegal"
How can I resolve it?
Thanks
That's because DateTime.Now converted to string by default contains time information (e.g. 8:53). Semicolon is illegal in path name.
If you meant only date to be in your file name, you could use:
String path2 = "C:\\temp" + DateTime.Now.ToString("d") + ".log";
(Edit) For some cultures this still can lead to invalid values, so as others pointed out, it is best to use explicit formatter:
String path2 = "C:\\temp" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
You want to escape your \ in the "" quoted string, and also there are characters in the result of DateTime.Now that cannot be in paths. You'll need to escape/replace those as well.
When you put DateTime.Now into a path, you risk adding characters that aren't valid as a path (like the : separator. That is the reason you get this error message.
You could replace it with a .:
string path2 = Path.Combine
( #"C:\temp\"
, DateTime.Now.ToString("yyyy-MM-dd.HH24.mm.ss")
, ".log"
);
DateTime.Now probably contains illegal characters depending on your local system settings. To get a valid and consistent file name independent on the culture the system is installed in you should create the log file name by hand, for instance like this:
String path2 = "C:\\temp" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log";
String path2 = String.Format("C:\\temp{0}.log", DateTime.Now.ToString("yyyyMMdd"));
Since filename cannot take "/" which was created by DateTime.Now.ToString("d") and hence creating issue.
Thank for reading my thread.
Here is the command line I like to call within my C# code:
C:\>"D:\fiji-win64\Fiji.app\ImageJ-win64.exe" -eval "run('Bio-Formats','open=D:\\Output\\Untitiled032\\ChanA_0001_0001_0001_0001.tif display_ome-xml')"
This is the exact command I can see from my console window, and it runs and gives me what I need. I want to run this command line from from my C# code, so there is escape character problem I don;t know how to handle
There are two strings I'd like to make them flexible
D:\fiji-win64\Fiji.app\ImageJ-win64.exe
D:\Output\Untitiled032\ChanA_0001_0001_0001_0001.tif
I am wondering how I can use string.Format() to formulate this command line?
This is my current code, it opens the image, but the display_ome-xml did not get called:
string bioformats = "Bio-Formats";
string options = string.Format("open={0} display_ome-xml", fileName.Replace("\\", "\\\\"));
string runCommand = string.Format("run(\"'{0}'\",\"'{1}'\")", bioformats, options);
string fijiCmdText = string.Format("/C \"\"{0}\" -eval {1}", fijiExeFile, runCommand);
where fijiExeFile works fins, it is just the runCommand keeps ignoring the display_ome-xml. Anyone has any suggestions? It is really really confusing. Thanks a lot.
As #Kristian pointed out, # can help here. It also appears that there may be some extra or misplaced \" in the code above. This seems to give the desired output string:
string fijiExeFile = #"D:\fiji-win64\Fiji.app\ImageJ-win64.exe";
string fileName = #"D:\\Output\\Untitiled032\\ChanA_0001_0001_0001_0001.tif";
string bioformats = "Bio-Formats";
string options = string.Format("open={0} display_ome-xml", fileName);
string runCommand = string.Format("run('{0}','{1}')", bioformats, options);
string fijiCmdText = string.Format("\"{0}\" -eval \"{1}\"", fijiExeFile, runCommand);
The easiest way is to use the verbatim string literal.
Just put a # before your string like so:
#"c:\abcd\efgh"
This will disable the backslash escape character
If you need " inside your string, you will have to escape the the quotation marks like so:
#"c:\abcd\efgh.exe ""param1"""
Your example could be:
String.Format(#"""{0}"" -eval ""run('Bio-Formats','open={1} display_ome-xml')""", #"D:\fiji-win64\Fiji.app\ImageJ-win64.exe", #"D:\Output\Untitiled032\ChanA_0001_0001_0001_0001.tif")
or
string p1 = "D:\\fiji-win64\\Fiji.app\\ImageJ-win64.exe";
string p2 = "D:\\Output\\Untitiled032\\ChanA_0001_0001_0001_0001.tif";
String.Format(#"""{0}"" -eval ""run('Bio-Formats','open={1} display_ome-xml')""", p1, p2);
I am trying to use a String.Format to create the following string
2MSFX.exe "C:\Users\Avidan\Documents\Visual Studio 2010\Projects\DefferedRenderer\DummyGame\DummyGameContent\Shaders\Clear.fx" "C:\Users\Avidan\Documents\Visual Studio 2010\Projects\DefferedRenderer\DummyGame\DummyGameContent\Shaders\Clear.mxfb"
so i am trying to use String.Format, but i just can't seen to get my head around it for some reason :|
The code is (where last 2 params are String.Empty):
String outputFile = Path.Combine(destDir, Path.ChangeExtension(Path.GetFileName(fxFile), "mgxf"));
String command = String.Format("\"{0}\" \"{1}\" \"{2}\" \"{3}\"", Path.GetFullPath(fxFile), Path.GetFullPath(outputFile), DX11Support, DebugSupport);
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = MGFXApp,
Arguments = command,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
But that appears to be giving me
\"C:\Users\Avidan\Documents\Visual Studio 2010\Projects\DefferedRenderer\DummyGame\DummyGameContent\Shaders\ClearGBuffer.fx\" \"C:\Users\Avidan\Documents\Visual Studio 2010\Projects\DefferedRenderer\DummyGame\DummyGameContent\Shaders\MGFX\ClearGBuffer.mgxf\" \"\" \"\"
If i use the verbatim string i can't get it to create the string i want.
Any Ideas?
Thanks.
Update
You should use String.Concat().
String.Concat("\"", Path.GetFullPath(fxFile), "\" " , Path.GetFullPath(outputFile), "\" " DX11Support,"\" " ,DebugSupport, "\"")
For a simple case like this, I wouldn't think it necessary, but you could create an extension method to automatically put quotes around the strings.
public static class StringExtensions
{
public static string Quotify(this string s)
{
return string.Format("\"{0}\"", s);
}
}
Then your command format looks like this:
String command = String.Join(" ",
Path.GetFullPath(fxFile).Quotify(),
Path.GetFullPath(outputFile).Quotify(),
DX11Support.Quotify(), DebugSupport.Quotify());
You need to use a combination of the # literal to avoid '\' squirlyness, and ""'s to make "'s
This example works for me:
string s = #"""C:\Test Dir\file.fx"" ""C:\Test Dir\SubDir\input.dat""";
Console.WriteLine(s);
Console output looks like this:
"C:\Test Dir\file.fx" "C:\Test Dir\SubDir\input.dat"
Just remember that two quotes makes a single quote, so the triple quote at the beginning and end of the string are the quote to start the string definition, and then a double quote to make a quote. Possibly one of the more confusing string formats out there, but that's how it works.