首页 > 解决方案 > 将文本文件读入对象

问题描述

经过数小时的努力,我需要将文本文件读入 Object. 我需要跳过文件中的前 15 行,但我不断收到Format Exception。请帮我。我还有很多东西要学。

异常是 => System.FormatException:输入字符串的格式不正确。在 System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) 在 System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) 在 System.Convert.ToInt32(String value) 在 PostTicketProject .TicketHelper.LoadData(Ticket[][]& ticket, String[] fileLines) 在 D:\CleanTicket\PostTicketProject\PostTicketProject\Ticket.cs:line 139

public void LoadData(ref Ticket[][] ticket, string[] fileLines)
    {                            
        try
        {

            //split each line into many columns using single white space, ignore tabs and double white space

                var data = fileLines[i].Replace("  ", string.Empty).Replace("\t", string.Empty).Split(' ');

                for (int i = 15; i< fileLines.Length; i++)
            {
                //split each line into many columns using single white space, ignore tabs and double white space

                var data = fileLines[i].Replace("  ", string.Empty).Replace("\t", string.Empty).Split(' ');

                for (int j = 0; j < fileLines[i].Length; j++)
                {
                    ticket[i][j] = new Ticket //this line throws format exception
                    {
                        ErrCode = Convert.ToInt32(data[j]),
                        DefectName = data[j],
                        Action = Convert.ToInt32(data[j]),
                        JudeTime = data[j],
                        UserName = data[j],
                    };
                }
            }                  
        }
        catch (FormatException FEx)
        {
            Console.WriteLine("Exception is => {0}", FEx);
        }
        catch (NullReferenceException NRefEx)
        {
            Console.WriteLine("Exception is => {0}", NRefEx);
        }
    }

读取文本文件的行可以读取并打印出内容。这里似乎没有问题

try
        {
            fileLines = File.ReadAllLines(@"D:\postTicket\repairTicket_post.txt");
        }
        catch (IOException IOEx)
        {
            Console.WriteLine("Failed to load file... Exception is => {0}", IOEx);
        }

我的文件结构如下

引脚开始日期时间 = 2019-03-14-01-45-05

引脚结束日期时间 = 2019-03-15-02-47-05

ups 明星日期跳过 = 19

操作员姓名 = ups

. . .

星数 = 12

0 [#]pass 0 2019-03-15-02-47-05 用户名

0 [#]pass 0 2019-03-15-02-47-05 用户名

0 [#]pass 0 2019-03-15-02-47-05 用户名

400000 [#]缺失[@]图像 1 2019-03-15-02-40-05 用户名

8000 [#]偏移量[@]图像 1 2019-03-15-02-46-10 用户名

0 [#]pass 0 2019-03-15-02-47-05 用户名

感谢你的帮助

标签: c#filetextnullreferenceexceptionformatexception

解决方案


我在您的代码中发现了一些错误。我会去扔它并解释我觉得奇怪的地方。

for (int i = 0; i< fileLines.Length; i++)
{
    while (i > 14)
    {

我想你打算写if (i > 14),因为现在一旦你到达第 15 行,你就会陷入无限循环。作为替代方案,if您可以使用i初始化14

var data = fileLines[i].Replace("  ", string.Empty).Replace("\t", string.Empty).Split(' ');

我猜你只是想删除行首和/或行尾的空格和制表符。在这种情况下,您可以使用Trim()/ TrimStart()/TrimEnd()但我可能会弄错,在这种情况下,您Replace的 s 是最好的解决方案。

for (int j = 0; j < fileLines[i].Length; j++)

在这个 for 循环中,您想遍历 中的拆分字符串data,但您使用j < fileLines[i].Length的是您的条件。这将为行中的字符数量而不是拆分子字符串的数量运行 for 循环。为此,您需要像这样遍历data数组i < data.Length

ticket[i][j] = new Ticket
{                                                                                               
    ErrCode = Convert.ToInt32(data[j]),
    DefectName = data[j],
    Action = Convert.ToInt32(data[j]),
    JudeTime = data[j],
    UserName = data[j],                               
};

在此部分中,您正在创建您的Ticket. 问题是首先你没有创建最有可能导致你的内部数组,NullReferenceException其次你总是使用相同的子字符串。在不太可能的情况下,您的ErrCode, DefectName,Action和都是数字JudeTime并且相同是正确的,但这可能不是您想要的。解决方案是使用一维数组而不是二维数组,并且不迭代吐出子字符串,而是使用数组创建对象。UserNamedata

更新代码:

public void LoadData(ref Ticket[] ticket, string[] fileLines)
{                            
    try
    {

        //to read and store the text file data in the ticket object

        ticket = new Ticket[fileLines.Length];

        for (int i = 14; i < fileLines.Length; i++)
        {
            //split each line into many columns using single white space, ignore tabs and double white space

            var data = fileLines[i].Replace("  ", string.Empty).Replace("\t", string.Empty).Split(' ');

            ticket[i] = new Ticket
            {                   
                ErrCode = Convert.ToInt32(data[0]),
                DefectName = data[1],
                Action = Convert.ToInt32(data[2]),
                JudeTime = data[3],
                UserName = data[4],
            };
        }
    }
    catch (FormatException FEx)
    {
        Console.WriteLine("Exception is => {0}", FEx);
    }
    catch (NullReferenceException NRefEx)
    {
        Console.WriteLine("Exception is => {0}", NRefEx);
    }
}

这假定行的格式为:

    <ErrCode> <DefectName> <Action> <JudeTime> <UserName>

如果顺序不同,则需要将索引调整到数据数组中。


推荐阅读