如何用c#在txt文件中每行设置前缀和删除字符后的字符。

问题描述 投票:0回答:1

你好,我从一个Web API中获取一些字符串。像这样

mail-lf0-f100.google.com,209.85.215.100
mail-vk0-f100.google.com,209.85.213.100
mail-ua1-f100.google.com,209.85.222.100
mail-ed1-f100.google.com,209.85.208.100
mail-lf1-f100.google.com,209.85.167.100
mail-ej1-f100.google.com,209.85.218.100
mail-pj1-f100.google.com,209.85.216.100
mail-wm1-f100.google.com,209.85.128.100
mail-io1-f100.google.com,209.85.166.100
mail-wr1-f100.google.com,209.85.221.100
mail-vs1-f100.google.com,209.85.217.100
mail-ot1-f100.google.com,209.85.210.100
mail-qv1-f100.google.com,209.85.219.100
mail-yw1-f100.google.com,209.85.161.100

它给了我一些字符串记录,我想这样做。业务.

  1. 我想让它一行一行的,就像它在原版中显示的那样。

  2. 我想把每行中逗号后面的内容都去掉。

  3. 我想在每一行前设置一个前缀,作为例子。

Example: Google.com to>> This is Dns: Google.com

这是我的代码。我应该编辑和我应该添加什么?

        string filePath = "D:\\google.txt";
        WebClient wc = new WebClient();
        string html = wc.DownloadString("https://api.hackertarget.com/hostsearch/?q=Google.com");
        File.CreateText(filePath).Close();
        string number = html.Split(',')[0].Trim();
        File.WriteAllText(filePath, number);
        MessageBox.Show("Finish");
c#
1个回答
1
投票

其实你已经很接近了。检查下面的解决方案

var filePath = @"C:\Users\Mirro\Documents\Visual Studio 2010\Projects\Assessment2\Assessment2\act\actors.txt";

WebClient client = new WebClient();
string html = client.DownloadString("https://api.hackertarget.com/hostsearch/?q=google.com");
string[] lines = html.Split(
    new[] { "\r\n", "\r", "\n" },
    StringSplitOptions.None
);

var res = lines.Select(x => (x.Split(',')[0]).Trim()).ToList();

//res.Dump();
System.IO.File.WriteAllLines(filePath, lines);

.Net Fiddle


0
投票

嗨,你好谢谢 Derviş Kayımbaşıoğlu(中文)

我也从另一个途径找到了我的解决方案

        string path = @"D:\Google.txt";
        var url = "https://api.hackertarget.com/hostsearch/?q=google.com";
        var client = new WebClient();
        //StreamWriter myhost = new StreamWriter(path);
        using (var stream = client.OpenRead(url))
        using (var reader = new StreamReader(stream))
        {
            string line;
            string realString;
            using (StreamWriter myhost = new StreamWriter(path))
            {
                while ((line = reader.ReadLine()) != null)
                {
                    realString = "This is the dns: " + line.Split(',')[0].Trim();

                    myhost.WriteLine(realString);
                }
            }
        }
        MessageBox.Show("Finish");
© www.soinside.com 2019 - 2024. All rights reserved.