Farhang
Farhang

Reputation: 13

How to set preftix and delete after character in each line in txt file with c#

Hello i'm getting some strings from a Web API Like This

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

it give me some string records and i want to do this Operations.

  1. I want to make it line by line like it show in original

  2. I want to remove everything after comma in eachline

  3. I want to set a prefix before each line for the example:

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

and This is my code . What should i edit and what should i add?

        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");

Upvotes: 0

Views: 41

Answers (2)

Farhang
Farhang

Reputation: 13

Hi Thanks to Derviş Kayımbaşıoğlu

Also i find my solution from another way

        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");

Upvotes: 0

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30565

you are actually close. Check the solution below

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

Upvotes: 1

Related Questions