【问题标题】:how to separate/filter an output string and write the separated data into different text boxes?如何分离/过滤输出字符串并将分离的数据写入不同的文本框中?
【发布时间】:2018-11-23 12:31:47
【问题描述】:

所以我有一个按钮和两个文本框。 我想点击一个按钮,它会执行 nslookup 然后我想:

-write the resolved hostname into one text box
-write the resolved ip adress into next text box 

目前为止有这个

    System.Diagnostics.Process p = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
                psi.FileName = "nslookup.exe";
                psi.Arguments = "google.com";

                psi.RedirectStandardOutput = true;
                psi.UseShellExecute = false;

                psi.CreateNoWindow = false;
                p.StartInfo = psi;
                p.Start();

                p.WaitForExit();

                System.IO.StreamReader output = p.StandardOutput;

                textbox1.Text = output.ReadToEnd().ToString();

所以现在它进行解析并将所有内容写入一个字符串。 如何过滤输出字符串并将字符串的特定部分写入单独的框中?

示例输出字符串将是:(它是单行字符串,但我将其写在表格中以便于理解)

Server:  EXAMPLE //this i dont need
Address:  EXAMPLE //this i dont need

Name:    google.com //i need this to be written to TextBox1
Address: 172.217.21.206 //i need this to be written to TextBox2

这样到底:

Textbox.Text = "google.com"
Textbox2.Text = "172.217.21.206"

稍后我想 ping textbox2 中的 ip 并让文本框在其可达时改变颜色,如果它可达,则 rdp 的按钮连接到该 ip,所以我需要它没有任何空格,只是一个字符串

我正在考虑将由空格分隔的每个单词写入一个数组,然后读取该数组并将匹配的内容写入框,如下所示:

string[] words = outputstring.Split(' ');

        foreach (var word in words)
        {
            System.Console.WriteLine($"<{word}>");
        }

但在我继续之前,我想问一下是否有更简单、更快捷的方法来做这件事,而我一起走错了方向?也许有一种方法可以从 nslookup 命令中返回特定参数?

【问题讨论】:

  • nslookup会返回几个ip地址,你要哪个?
  • 请记住,正如 [nslookup] wiki 中所说,对 nslookup 的一般支持不在此处讨论。
  • 为什么不使用 Dns.GetHostByName ("google.com");来自 System.Net,而不是使用结果来填充文本框?
  • 是的 dns.gethostbyname 是最好和最快的方法,我在互联网上到处寻找类似的东西但找不到它,我是初学者

标签: c# .net string nslookup


【解决方案1】:

可以使用Dns.GetHostEntry代替手动调用外部进程:

IPHostEntry hostInfo = Dns.GetHostEntry("example.com");
textbox1.Text = hostInfo.HostName;
textbox2.Text = hostInfo.AddressList[yourIndex].ToString();

【讨论】:

  • 那么我在“yourIndex”中放了什么?如果我放 1 或 2 它会抛出一个超出范围异常的索引
  • @JohnLinaer 这取决于你想得到什么,例如google.com 它返回大约10 地址,你想显示什么?你的任务是什么?
  • 如果它是用户输入,你可能需要把它放在try/catch,因为如果找不到主机地址,它会抛出SocketException
  • 好吧,我的网络中有服务器,所以服务器主机名是 example.domain.com,所以我想对“example”进行 nslookup,它会返回 example.domain。 com 并且应该写入文本框中。当我使用 cmd 执行 nslookup 时,它会显示 2 个名称,第一个是通常是第一个的域,然后是第二个是我要查找的主机名,所以基本上我希望它返回服务器的主机名 + 域没有用户输入,我只想做一个服务器状态检查器,看看服务器是否在线 + 显示主机名和 IP 地址等信息
  • @JohnLinaer 有问题的 IP 地址发生了什么?
【解决方案2】:

正则表达式可以在这里为您提供帮助。以下是检索名称的方法,因为地址类似:

Regex.Match(text, @"Name: *(?<name>[^ ]+)").Groups["name"].Value

【讨论】:

  • 如何处理带有“名称:”的多行?
猜你喜欢
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
  • 2015-11-07
  • 2013-09-23
  • 1970-01-01
相关资源
最近更新 更多