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);
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.
In my block of code below, I am triyng to replace words ending with -ing with a static text "------". However, this doesn't seem to work and throws --- all over the place. What am I doing wrong?
string ingString = "I like programming, running, jobs and swimming.";
string ingWords = #"[^\\b\\w+(ing\\b)$]";
string staticLine = "------";
replaceString = Regex.Replace(ingString, ingWords, staticLine);
It should read "I like ------, ------, jobs and ------."
Thanks
This will do it:
string ingString = "I like programming, running, jobs and swimming.";
string ingWords = #"\w+ing\b";
string staticLine = "------";
Console.WriteLine(Regex.Replace(ingString, ingWords, staticLine));
Output:
I like ------, ------, jobs and ------.
Now answering to your question:
What am I doing wrong?
You regex:
[^\\b\\w+(ing\\b)$]
When you use brackets [...] it represents a set of characters, so the engine is trying to match all caracters inside your set, thats why its replacing a lot of chars with -----
Your regex isn't right. Try this: \w*ing\b
Taken from another question but modified to suit your need.
I have an example username:
corp\myusername
So if I put this in C# it wants to escaoe it with "\" so it turns out to be:
corp\\myusername but I need to to be corp\myusername. Any ideas how to get it to work?
Thanks much
using verbatim string
string username = #"corp\\myusername"
or
"\\" = \ so "\\\\" = \\
string username = "corp\\\\myusername"
try adding a "#" symbol in front of the string like this:
String.Format(#"corp\myusername")
or double up the "\" to escape the escape :)
Use a verbatim string literal.
http://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx
Precede the literal with "#" character and you can then type that.
I imagine you're trying to separate the domain from the user name, to get the username for your application when using Windows authentication in your site, yes? I also ran into the issue where some machines would return the value as upper case, and some as lower case, so be careful to force the case in your source code (or database)!
string windowsLogin = HttpContext.Current.User.Identity.Name;
int hasDomain = windowsLogin.IndexOf(#"\");
if (hasDomain > 0)
{
windowsLogin = windowsLogin.Remove(0, hasDomain + 1);
}
return windowsLogin.ToLower();
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.