如何删除列表中每个字符串的空格?

时间:2015-08-25 20:55:28

标签: c# listview cmd whitespace

我有一个列表,想要通过命令行运行ListViewItem中的每个项目。目前在我看来,我的列表是在文本之前传播每个带有空格的项目,这会导致命令行无法将字符串识别为有效数据。如何删除列表中每个字符串值的开头和结尾的空格?

注意:您可以在标记为STAGE2的区域中查看列表的结构

        private void wifiButton_Click(object sender, EventArgs e)
    {
        // STAGE 1 -- Query wifi profiles saved on device and isolate SSIDs
        Process cmd = new Process();
        cmd.StartInfo.FileName = "netsh.exe";
        System.Threading.Thread.Sleep(50);
        cmd.StartInfo.Arguments = "wlan show profiles";
        cmd.StartInfo.UseShellExecute = false;
        cmd.StartInfo.RedirectStandardOutput = true;
        cmd.StartInfo.RedirectStandardError = true;
        cmd.Start();
        //* Read the output (or the error)
        string output = cmd.StandardOutput.ReadToEnd();
        textBox3.Text = output;
        cmd.WaitForExit();
        System.Threading.Thread.Sleep(50);


        // output would be set by earlier code
        // STAGE 2 remove extra data in string down to the SSID name, then add insividual results into a list
        var regex = new Regex(@" User Profile\s+:(.*)");
        var resultList = new List<string>();

        foreach (Match match in regex.Matches(output))
        {
            output = string.Concat(output.Split(' '));
            resultList.Add(match.Groups[1].ToString());
            textBox4.Items.Add(match.Groups[1].ToString());
        }

        System.Threading.Thread.Sleep(500);
        // STAGE 3 For each item in the list created in stage 2, run individual SSID name through netsh and add results to textbox5. 
        foreach (ListViewItem item in textBox4.Items)
        {
            //arg = arg.Remove(0, 15);
            Process cmd2 = new Process();
            cmd2.StartInfo.FileName = "netsh.exe";
            cmd2.StartInfo.Arguments = "wlan show profiles name=" + item;  
            cmd2.StartInfo.UseShellExecute = false;
            cmd2.StartInfo.RedirectStandardOutput = true;
            cmd2.StartInfo.RedirectStandardError = true;
            cmd2.Start();
            //* Read the output (or the error)
            string output2 = cmd2.StandardOutput.ReadToEnd();
            textBox5.Text += output2;
            cmd2.WaitForExit();
        }
     }

2 个答案:

答案 0 :(得分:1)

在这一行

 cmd2.StartInfo.Arguments = "wlan show profiles name=" + item;  

您正在将ListViewItem连接到字符串。这是通过调用ListViewItem的ToString方法来解决的,它生成类似这样的东西

 cmd2.StartInfo.Arguments = "wlan show profiles name=ListViewItem: {...whatever...}

当然这不是有效的netsh命令。

您需要将其更改为

 cmd2.StartInfo.Arguments = "wlan show profiles name=" + item.Text.Trim();  

(Trimmin以防有效地使Regex保留一些空白)

答案 1 :(得分:0)

使用Trim();

string stringToTrim = "   asdf    ";
Console.Log(stringToTrim.Trim());

// Output: 'asdf'