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.
Related
So I have this string which I have to trim and manipulate a little with it.
My string example:
string test = "studentName_123.pdf";
Now, what I want to do is somehow extract only the _123 part and at the end I need to have studentName.pdf
What I have tried:
string test_extracted = test.Substring(0, test.LastIndexOf("_") )+".pdf";
This also works but the thing is that I don't want to add the ".pdf" suffix at the end of the string manually because I can have strings that are not pdf, for ex. studentName.docx , studentName.png.
So basically I just want the "_123" part removed but still keep the remain part after that.
I think this might help you:
string test = "studentName_123.pdf";
string test_extracted = test.Substring(0, test.LastIndexOf("_") )+ test.Substring(test.LastIndexOf("."),test.Length - test.LastIndexOf(".") );
Using Remove(int startIndex, int count):
string test = "studentName_123.pdf";
string test_extracted = test.Remove(test.LastIndexOf("_"), test.LastIndexOf(".") - test.LastIndexOf("_"));
Sounds like you mean something like this?
string extension = Path.GetExtension(test);
string pdfName = Path.GetFileNameWithoutExtension(test).Split('_')[0];
string fullName = pdfName + extension;
Since you know what value you will always be replacing in your strings, "_123", to base on your example, just utilize the replace method and replace it with nothing since the method expects two arguments;
string test_extracted = test.replace('_123', '');
This could be solved with a regular expression like this
(\w*)_.*(\.\w*) where the first capture group (\w*) matches everything before the underscore and the second group (\.\w*) matches the file extensions.
Lastly we just have to concat the groups without the stuff inbetween like so:
string test = "studentName_123.pdf";
var regex = Regex.Match(test, #"(\w*)_.*(\.\w*)");
string newString = regex.Groups[1].Value + regex.Groups[2].Value;
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 have grabbed some data from a website.A string which is named as urlresult in the data is "http:\/\/www.cnopyright.com.cn\/index.php?com=com_noticeQuery&method=wareList&optionid=1221&obligee=\u5317\u4eac\u6c83\u534e\u521b\u65b0\u79d1\u6280\u6709\u9650\u516c\u53f8&softwareType=1".
what I want to do is to get rid of the first three char #'\' in the string urlresult above . I have tried the function below:
public string ConvertDataToUrl(string urlresult )
{
var url= urlresult.Split('?')[0].Replace(#"\", "") + "?" + urlresult .Split('?')[1];
return url
}
It returns "http://www.cnopyright.com.cn/index.php?com=com_noticeQuery&method=wareList&optionid=1221&obligee=\\u5317\\u4eac\\u6c83\\u534e\\u521b\\u65b0\\u79d1\\u6280\\u6709\\u9650\\u516c\\u53f8&softwareType=1" which is incorrect.
The correct result is "http://www.cnopyright.com.cn/index.php?com=com_noticeQuery&method=wareList&optionid=1221&obligee=北京沃华创新科技有限公司&softwareType=1"
I have tried many ways,but it hasn't worked.I have no idea how to get the correct result.
I think you may be misled by the debugger because there's no reason that extra "\" characters should get inserted by the code you provided. Often times the debugger will show extra "\" in a quoted string so that you can tell which "\" characters are really there versus which are there to represent other special characters. I would suggest writing the string out with Debug.WriteLine or putting it in a log file. I don't think the information you provided in the question is correct.
As proof of this, I compiled and ran this code:
static void Main(string[] args)
{
var url = #"http:\/\/www.cnopyright.com.cn\/index.php?com=com_noticeQuery&method=wareList&optionid=1221&obligee=\u5317\u4eac\u6c83\u534e\u521b\u65b0\u79d1\u6280\u6709\u9650\u516c\u53f8&softwareType=1";
Console.WriteLine("{0}{1}{2}", url, Environment.NewLine,
url.Split('?')[0].Replace(#"\", "") + "?" + url.Split('?')[1]);
}
The output is:
http:\/\/www.cnopyright.com.cn\/index.php?com=com_noticeQuery&method=wareList&optionid=1221&obligee=\u5317\u4eac\u6c83\u534e\u521b\u65b0\u79d1\u6280\u6709\u9650\u516c\u53f8&softwareType=1
http://www.cnopyright.com.cn/index.php?com=com_noticeQuery&method=wareList&optionid=1221&obligee=\u5317\u4eac\u6c83\u534e\u521b\u65b0\u79d1\u6280\u6709\u9650\u516c\u53f8&softwareType=1
You can use the System.Text.RegularExpressions.Regex.Unescape method:
var input = #"\u5317\u4eac\u6c83\u534e\u521b\u65b0\u79d1\u6280\u6709\u9650\u516c\u53f8";
string escapedText = System.Text.RegularExpressions.Regex.Unescape(input);
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
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);