Passing array of arguments in command line - c#

I had look this question about Passing command line arguments in C#.
But in my case I have to pass array of parameters to the calling .exe file.
e.g.
var arr = new string[] {"Item title","New task","22","High Priority"}
Is it possible to use Process.Start() with exe path along with the array
I have the .exe path
const string path = #"C:\Projects\Test\test.exe";
Thanks

One option is to put the array in one string so it is viewed as one argument by the method. In your method, you can then parse that one argument. Something like:
"Item title, New task, 22, High Priority"
You can use your existing array by doing:
var arrAsOneString = string.Join(", ", arr);
Inside your method, do:
var values = argument.Split(',').Select(x => x.Trim());
I added the trim to do away with spaces.

Its not possible to pass array as argument, you can pass a string with Comma Separator:
ProcessStartInfo info = new ProcessStartInfo();
info.Arguments = "Item title,New task,22,High Priority"

Please try this:
var arr = new string[] {"Item title", "New task", "22", "High Priority"};
const string path = #"C:\Projects\Test\test.exe";
const string argsSeparator = " ";
string args = string.Join(argsSeparator, arr);
Process.Start(path, args);

Related

read data from file with StreamReader into array of line 1

StreamReader text = new StreamReader(#textBox1.Text.ToString());
String tempArray = text.ReadToEnd();
char[] charA = tempArray.ToCharArray();
Console.Write(charA);
output is like that
****4****
**26*71**
871***694
*6*****4*
2*59*67*8
*8*****2*
658***471
**94*85**
****7****
but ı want to write and save 1d array on 1 row simple ;
****4****
26*71
871***694
*6*****4*
2*59*67*8
*8*****2*
658***471
94*85
****7****
how can ı split this ?
There's a lot going on in the code you've shared:
StreamReader text = new StreamReader(#textBox1.Text.ToString());
String tempArray = text.ReadToEnd();
char[] charA = tempArray.ToCharArray();
Console.Write(charA);
textBox1.Text already is a string, so you don't need the .ToString() behind that.
By the way you don't need to prefix a field with a # unless it's the field has the same name as a keyword. You're free to do it anyway if you like, though).
StreamReader text = new StreamReader(textBox1.Text);
String tempArray = text.ReadToEnd();
char[] charA = tempArray.ToCharArray();
Console.Write(charA);
Next, if all you want to do with the file is read all its contents as a string, you might want to use File.ReadAllText() as it doesn't keep the file open:
String tempArray = File.ReadAllText(textBox1.Text);
char[] charA = tempArray.ToCharArray();
Console.Write(charA);
The console outputs multiple lines but the char[] still really is a 1D array. The problem is that there are newline characters in the file, which get processed by the console.
If you want to remove these newlines, it's easier to do so while you're still working with a string - because there are quite a few built-in features for this. Someone already commented using string.Replace("\r\n", "") to do this trick:
String tempArray = File.ReadAllText(textBox1.Text);
tempArray = tempArray.Replace("\r", "");
tempArray = tempArray.Replace("\n", "");
char[] charA = tempArray.ToCharArray();
Console.Write(charA);

C# - Convert string, to a two dimensional string array

I can't seem to figure this out.
I want to convert this:
string foobarString = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
To a two dimensional array (or list) so it looks like this:
fooBarArray[0] = Array['Foo', "bar"];
fooBarArray[1] = Array['Foo', "bar"];
fooBarArray[2] = Array['Foo', "bar"];
... etc.
I have tried spliting by ("],") and then cleaning the string and creating an array afterwards. But it's just to damn UGLY!
I want a cleaner version. Is there no method built in for such a method in C#?
// Thanks
Since your question is not giving us enough information I will assume that you are trying to convert some JSON into an array of strings.
As far as I know there is no build in method in C# for this.
You could use an extension for this. Newtonsoft JSON
After installing this package you will be able to use the following code:
string foobarString = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<string[][]>(foobarString);
First, split it by "[[", "], [", "]]"
var array1 = foobarString.Split(new string[] {"[[", "], [", "]]"}, StringSplitOptions.RemoveEmptyEntries);
array1 will contain "'Foo', 'bar'", "'Foo', 'bar'", "'Foo', 'bar'"
Then you can split every element by ','
var fooBarArray = array1.Select(x => x.Split(',').ToArray()).ToArray()
You can do it in one line
var fooBarArray = foobarString.Split(new string[] { "[[", "], [", "]]" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(',').ToArray()).ToArray()
You could use Regex to get the array elements from your source string and then convert the matches into your arrays. Something like this should do the trick:
var input = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
// search for [' more than one word character, put them into group a ',
// more than one whitespace ' more than one word character, put them into group b ']
var arrayMatches = Regex.Matches(input, #"\['(?<a>[\w]+)',\s+'(?<b>[\w]+)'\]");
var arrays = new List<string[]>();
foreach (Match arrayMatch in arrayMatches)
{
// if the match was unsuccessful, take the next match
if(!arrayMatch.Success)
continue;
// create a new string array with element in group a as first element and the element in groub b as the second one
var array = new [] {arrayMatch.Groups["a"].Value, arrayMatch.Groups["b"].Value};
arrays.Add(array);
}
// convert list to array
return arrays.ToArray();
{
const string oldString = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<List<string>>>(oldString);
}
There you can find some examples. The String.Split function returns an array so you can do
string[] lines = foobarString.Split(new char[]{']'}, StringSplitOptions.RemoveEmtpyEntries);
fooBarArray[0] = lines[i].Split(new char[]{'[',']', ','}, StringSplitOptions.RemoveEmtpyEntries);
Take a look at this thread: multidimensional-array-vs

Replace specific string in large string

I'm writing a small WPF Application which helps my company to update costumer projects. I have a list of SQL-Files which I have to execute. Now these scripts are always written with a "USE [Insert_Database]". I read the whole content of a script into a string, but my Replace method doesn't seem to do anything.
string content = File.ReadAllText(file);
content.Replace("Insert_Database", Database.Name);
SqlScriptsList.Add(new SqlScriptModel {Name = Path.GetFileName(file), Path = file, ScriptContent = content});
String.Replace returns the modified string, so it should be:
content = content.Replace(....);
This method does not modify the value of the current instance.
Instead, it returns a new string in which all occurrences of oldValue
are replaced by newValue.
You can use replace function as follow on strings
str = str.Replace("oldstr","newstr");
if oldstr is found in the str then it will be replaced by new str
You aren't using new value when you call replace.
string content = File.ReadAllText(file);
content = content.Replace("Insert_Database", Database.Name);
SqlScriptsList.Add(new SqlScriptModel {Name = Path.GetFileName(file), Path = file, ScriptContent = content});
for reference: the MSDN doc for replace https://msdn.microsoft.com/en-us/library/system.string.replace(v=vs.110).aspx

Call Process in C# with String args[]

I want to call a Process from C# with multiple parameters.
When i call:
ProcessStartInfo info = new ProcessStartInfo();
...
info.Arguments = "argument";
Process.Start(info);
i can only set a String as attribute. (Same to all types of the Start method)
Is there a way to set a String[] as arguments or how does this String getting interpreted?
Because on the other side
static void Main(string[] args)
i am getting a String[].
Thanks in advance.
Technically you can do it like that:
string[] args = new String[] {"argument1", "argument2", "argument3"};
...
info.Arguments = String.Join(" ", args);
the restriction is that args should not have arguments with spaces
Is there a way to set a String[] as argument?
No you can't do this, since the type of ProcessStartInfo.Arguments is string. Hence you can assign to it an array of strings.
You could pass to this string the parameters as follows:
info.Arguments = "argument1 argument2 argument3";
and your .exe will be executed as you were passing an array of strings with elements (argument1,argument2,argument3).

how to parse main arguments?

How can I find this information :
think we started this process :
testFile.exe i- 100 k- "hello" j-"C:\" "D:\Images" f- "true"
Now how can I get main argument when application started so I have :
int i = ... ; //i will be 100
string k = ... ; // k = hello
string[] path = ... ; // = path[0] = "C:\" , path[1] = "D:\Images"
bool f = ... ; // f = true;
regards
The arguments are passed to the Main function that is being called:
static void Main(string[] args)
{
// The args array contain all the arguments being passed:
// args[0] = "i-"
// args[1] = "100"
// args[2] = "k-"
// args[3] = "hello"
// ...
}
Arguments are in the same order as passed in the command line. If you want to use named arguments you may take a look at this post which suggests NDesk.Options and Mono.Options.
You can use Environment.CommandLine or Environment.GetCommandLineArgs()
String[] arguments = Environment.GetCommandLineArgs();
More info on MSDN
As already answered, you can use the string[] args parameter or Environment.GetCommandLineArgs(). Note that for CLickOnce deployed apps you need something else.
You can do your own processing on the string[] or use a library, like this one on CodePlex.
For some tricky details on spaces in filenames and escaping quotes, see this SO question.
You could use NDesk.Options. Here is their documentation.

Categories