Reputation: 71
I am developing an application for managing Personal Hotspot of a Laptop (Windows of Course). I'm having a little difficulty in changing the Hotspot Name. Here is my Code:
//For CMD Command
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new
System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.FileName = "CMD.exe";
startInfo.CreateNoWindow = true;
//Reading User Input in textBox1:
string name = textBox1.Text;
//CMD Argument:..., Which is currently written wrong to make it Easy to
//understand the problem
startInfo.Arguments = "/C netsh wlan set hostednetwork ssid="name";
process.StartInfo = startInfo;
process.Start();
Here, In the Arguments
line, the syntax is wrong. The value assigned to Arguments
should be a single string. I need to incorporate name
, that has a dynamic value, with the rest of the string that is constant. How do I do that?
Upvotes: 2
Views: 282
Reputation: 1870
There are several ways you can create a dynamic string:
For your specific case, Concatenation is the best choice as your string
is very simple.The reason you would choose this method for your case is because it is very light as compared to other methods and has a clean enough syntax.
startInfo.Arguments = "/C netsh wlan set hostednetwork ssid=" + name;
For anything more complicated, string.Format
is a popular go to. You would generally use it to combine more complex strings
than your example. This tutorial covers the subject thoroughly.
startInfo.Arguments = string.Format("/C netsh wlan set hostednetwork ssid={0}", name);
The release of C#6.0
included a neat feature: interpolated strings. It is for the most part just syntactic sugar for string.Format
, where the line below is turned into the line above at compile time. There are subtle differences, but those are not important in this thread.
startInfo.Arguments = $"/C netsh wlan set hostednetwork ssid={name}";
And lastly, if you need to change a string more than a few times (I usually use the rule of 5 - i.e. a string changes more than 5 times), I would use the StringBuilder
class. A great application, among many others, would be a long loop that modifies a certain string each iteration. See This Tutorial.
In this case, the Garbage Collector will thank you for a using a StringBuilder
!
Upvotes: 2
Reputation: 82474
Unless I'm missing something here, seems to me that a simple string concatenation would do it:
startInfo.Arguments = "/C netsh wlan set hostednetwork ssid=" + name;
Upvotes: 4