【问题标题】:ASP.NET MVC : how to split a row in a text file by fixed-width and pass to a modelASP.NET MVC:如何按固定宽度拆分文本文件中的行并传递给模型
【发布时间】:2021-04-07 02:25:17
【问题描述】:

我正在尝试使用System.IO.File.ReadAllLines() 读取一个文本文件,然后将数组的每一行输入到我将传递给视图的模型中。

我可以成功读取文本文件,但我想将每一行分成几列。文本文件具有固定宽度作为分隔符,这是我失败的地方。

例如,我知道逗号是否是分隔符 Project = row.Split(',')[0] 是正确的,但我如何处理固定宽度?

我的动作如下。

我知道第一列从@字符 0 开始,第二列从 26 开始,第三列从 82 开始,第四列从 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);
}

【问题讨论】:

  • 尝试使用 substring 代替:row.SubString(0,16), row.SubString(26, 56), row.SubString(82, 24), row.SubString(106) 我通常添加一个 Trim () 到每个。

标签: c# asp.net-mvc


【解决方案1】:

如果您使用的是 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
                });
            }
        }

否则:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-15
    • 2018-06-18
    • 2013-04-25
    • 1970-01-01
    • 2015-04-01
    • 2010-10-26
    • 1970-01-01
    • 2014-02-22
    相关资源
    最近更新 更多