Home > OS >  What Should I Do To Parse Text Inside A File?
What Should I Do To Parse Text Inside A File?

Time:12-11

I want to read the info1.txt file and want to write in another text file info2.txt in this manner.

Id      Name     Address      DOB      Phone
1       abcd      efg      1/16/2021  987654323
2       hijkl     mno      2/16/2021  678987652

The contents of the info1.txt file are as follows:

Id:1
Name:abcd
Address:efg
DOB:1/16/2021 3:31:22 PM
Phone:987654323

And the info2.txt would be like above table format that I mentioned,also want to remove "3:31:22 PM". The code block I developed to solve this problem is available below:

static void Main(string[] args)
{
    FileStream fsRead = new FileStream("E:\\info1.txt", FileMode.Open, FileAccess.Read);
    StreamReader srObj = new StreamReader(fsRead);
    FileStream fsWrite = new FileStream("E:\\info2.txt", FileMode.Create, FileAccess.Write);
    StreamWriter swObj = new StreamWriter(fsWrite);

    while (srObj.Peek() > 0)
    {
        string str;
        string[] strArray;
        
        str = srObj.ReadLine();
        str = str.Replace(" 3:31:22 PM", "");
        strArray = str.Split(':');

        if (strArray.Length > 1)
        {
            swObj.Write(strArray[1]);
            swObj.Write(" ");
        }
    }
    
    swObj.Close();
    fsWrite.Close();
    srObj.Close();
    fsRead.Close();

    Console.ReadKey();
}

CodePudding user response:

I would parse the file into a list of dictionaries where each dictionary's keys are the columns.

First split the file lines into an array of strings. You can use File.ReadAllLines for that. Then send the array to this function that parses the lines.

public static List<Dictionary<string, string>> Parse(string [] lines)
{
    List<Dictionary<string, string>> data = new List<Dictionary<string, string>>();
    Dictionary<string, string> temp = new Dictionary<string, string>();
    foreach (var line in lines) {
        var parts = line.Split(new[] { ':' }, 2);
        if (parts.Length == 2) {
            temp[parts[0]] = parts[1];
        }
        else {
            if (temp.Count > 0) data.Add(temp);
            temp = new Dictionary<string, string>();
        }
    }
    if (temp.Count > 0) data.Add(temp);
    return data;
}

Then, make a function to write the list to a file.

public static void PrintTable(List<Dictionary<string, string>> users, TextWriter stream)
{
    if (users.Count == 0) return;
    
    // Print the header line
    foreach(var pair in users[0]) {
        stream.Write("{0,-12}", pair.Key);
    }
    stream.WriteLine();
    
    foreach (var user in users) {
        foreach(var pair in user) {
            // Special handling for DOB
            if (pair.Key == "DOB") stream.Write("{0,-12}", pair.Value.Split(' ')[0]);
            else stream.Write("{0,-12}", pair.Value);
        }
        stream.WriteLine();
    }
}
  • Related