ASP.NET MVC : how to split a row in a text file by fixed-width and pass to a model

Viewed 205

I am trying to read a text file using System.IO.File.ReadAllLines() and then input each row of the array into a model which I will pass to a view.

I can read the text file successfully but I want to split each row into columns. The text file has fixed-width as the delimiter, and this is where I am failing.

For example I know if comma was the delimiter Project = row.Split(',')[0] would be correct but how do I handle fixed-width?

My action is below.

I know the first column starts @ character 0, 2nd at 26, 3rd at 82 and 4th at 106

public ActionResult Index()
{
    string[] texts = System.IO.File.ReadAllLines(Server.MapPath("~/App_Data/Test/test.txt"));
    texts = texts.Skip(2).ToArray();

    List<Alarm_DataModel> Alarm_Data = new List<Alarm_DataModel>();

    foreach (string row in texts)
    {
        if (!string.IsNullOrEmpty(row))
        {
            Alarm_Data.Add(new Alarm_DataModel
                               {
                                   Project = row.Split('0')[0],
                                   Point = row.Split('26')[1],
                                   TimeStamp = row.Split('82')[2],
                                   DataValue = row.Split('106')[3],
                               });
        }
    }

    ViewBag.Data = texts;

    return View(Alarm_Data);
}
1 Answers

if you are using C# 8+:

foreach (string row in texts)
        {
            if (!string.IsNullOrEmpty(row))
            {
                Alarm_Data.Add(new Alarm_DataModel
                {
                    Project = new string(row[0..25]),
                    Point = new string(row[26..85]),
                    TimeStamp = new string(row[86..105]),
                    DataValue = new string(row[106..^0]), //take the rest
                });
            }
        }

otherwise:

foreach (string row in texts)
        {
            if (!string.IsNullOrEmpty(row))
            {
                Alarm_Data.Add(new Alarm_DataModel
                {
                    Project = row.SubString(0,26),
                    Point = row.SubString(26, 60), //60 comes from 86 - 26
                    TimeStamp = row.SubString(86,30),  //30 comes from 106 - 86
                    DataValue = row.SubString(106), //take the rest
                });
            }
        }
Related