Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...