读取.csv文件并将其存储在数组中?

时间:2014-01-25 18:56:42

标签: c# csv

我正在进行一项将.csv文件中的数据存储到数组中的赋值。我用过(int i = 0; i< data.Length; i ++),但是i ++无法访问。看看你将会了解的代码。问题在于可能只是存储。如果可以,请帮助我。

由于

static void Load(string[] EmployeeNumbers, string[] EmployeeNames, string[] RegistrationNumbers, float[] EngineCapacityArray,
        int[] StartKilometresArray, int[] EndKilometresArray, string[] TripDescriptions, bool[] PassengerCarriedArray,
        ref int NextAvailablePosition, ref int RecordCount, ref int CurrentRecord)
    {
        string str = "";
        FileStream fin;
        string[] data;
        bool tval = false;
        // Open the input file
        try
        {
            fin = new FileStream("carallowance.csv", FileMode.Open);
        }
        catch (IOException exc)
        {
            Console.WriteLine(exc.Message);
            return;
        }
        // Read each line of the file
        StreamReader fstr_in = new StreamReader(fin);
        try
        {
            while ((str = fstr_in.ReadLine()) != null)
            {
                // Separate the line into the name and age
                data = str.Split(';');
                if (data.Length == 8)
                {
                    Console.WriteLine("Error: Could not load data from the file. Possibly incorrect format.");
                }
                for (int i = 0; i < data.Length; i++)
                {
                    EmployeeNumbers[NextAvailablePosition] = data[0];
                    EmployeeNames[NextAvailablePosition] = data[1];
                    RegistrationNumbers[NextAvailablePosition] = data[2];
                    tval = float.TryParse(data[3], out EngineCapacityArray[NextAvailablePosition]);
                    tval = int.TryParse(data[4], out StartKilometresArray[NextAvailablePosition]);
                    tval = int.TryParse(data[5], out EndKilometresArray[NextAvailablePosition]);
                    TripDescriptions[NextAvailablePosition] = data[6];
                    tval = bool.TryParse(data[7], out PassengerCarriedArray[NextAvailablePosition]);

                    CurrentRecord = NextAvailablePosition;
                    NextAvailablePosition++;
                    RecordCount++;
                    Console.WriteLine("Your file is sucessfully loaded.");

                    break;
                }
            }
        }
        catch (IOException exc)
        {
            Console.WriteLine(exc.Message);
        }
        // Close the file
        fstr_in.Close();
    }

4 个答案:

答案 0 :(得分:1)

因为休息而无法到达;在循环结束时。这迫使for循环在第一次执行后停止执行。如果你在一个控制台项目中运行它,它只会输出一个0。

    private static void Main(string[] args)
    {
        for (int i = 0; i < 2; i++)
        {
            Console.WriteLine(i.ToString());
            break;
        }
    }

答案 1 :(得分:1)

也许代码审查stackexchange会更好。这里有很多问题。

首先,我们可以简化使用框架callto File.ReadAllLines(...)。这将为您提供文件中所有行的序列。然后你想把它转换成一系列数组(拆分为',')。这很简单:

var splitLines = File.ReadAllLines("\path")
                     .Select(line => line.Split(new char[] { ',' }));

现在你可以用foreach迭代splitLines。

(我注意到你似乎将值设置到传入的数组中。尽量不养成这样做的习惯。这些副作用和滥用参考参数很容易变得非常脆弱。 )

然后这看起来很奇怪:

if (data.Length == 8)
{
    Console.WriteLine("...");
}

我怀疑你的比较运算符中只有一个拼写错误(应该是!=)。如果您不关心在错误数据上写入控制台,您只需在转换后过滤掉错误数据。看起来像是:

var splitLines = File.ReadAllLines("\path")
                     .Select(line => line.Split(new char[] { ',' }))
                     .Where(data => data.Length == 8);

现在回想一下[int/float].TryParse(s, out v)将v设置为已解析的值或类型的默认值,如果解析成功则返回true。那个“或默认”在这里很重要。这意味着如果无法解析它们就会填充错误/无效值,并且您对tval一无所知。

考虑一个表示数据集记录的对象/类型,而不是所有这些。看起来您正试图从csv表中跟踪员工里程数。这看起来像是:

public class MileageRecord
{
    public string Name { get; set; }
    /* More properties */
    public MileageRecord FromCSV(string[] data)
    {
        /* try parsing, if not then log errs to file and return null */
    }
}

现在你已经摆脱了所有的副作用,整个事情变得更加清洁了。从文件加载所有这些数据就像这样简单:

public static IEnumerable<MileageRecord> Load()
{
    return File.ReadAllLines("\path")
               //.Skip(1) // if first line of the file is column headers
               .Select(line => line.Split(new char[] { ',' }))
               .Where(data => data.Length == 8)
               .Select(data => MileageRecord.FromCSV(data))
               .Where(mileage => mileage != null);
}

答案 2 :(得分:0)

这段代码:

            NextAvailablePosition++;
            RecordCount++;
            Console.WriteLine("Your file is sucessfully loaded.");

            break; // <-- this instruction
        }

使您退出for循环,而无法增加i值。

答案 3 :(得分:0)

问题:你应该在break(在if condition循环内)添加while语句,这样如果数据长度确实如此不匹配8然后它将从循环中断/退出。但你错误地在break内添加了for-loop。这就是为什么它只是第一次执行并且循环出来。

解决方案:break语句从for循环移到while循环中的if-blcok。

试试这个:

第1步:从for循环中删除break语句。

                CurrentRecord = NextAvailablePosition;
                NextAvailablePosition++;
                RecordCount++;
                Console.WriteLine("Your file is sucessfully loaded.");

               // break; //move this statement to inside the if block

第2步:break语句放入if循环中的if-block中。

          if (data.Length == 8)
            {
                Console.WriteLine("Error: Could not load data from the file. Possibly incorrect format.");
                break;
            }

建议:您可以使用File.ReadAllLines()方法重新编写代码,以避免以下复杂性:

static void Load(string[] EmployeeNumbers, string[] EmployeeNames, string[] RegistrationNumbers, float[] EngineCapacityArray,
  int[] StartKilometresArray, int[] EndKilometresArray, string[] TripDescriptions, bool[] PassengerCarriedArray,
  ref int NextAvailablePosition, ref int RecordCount, ref int CurrentRecord)
  {
           string str = "";        
           string[] data;
           bool tval = false;
           String [] strLines=File.ReadAllLines("carallowance.csv");
           for(int i=0;i<strLines.Length;i++)
           {
            str=strLines[i];
            data = str.Split(';');
            if (data.Length == 8)
            {
                Console.WriteLine("Error: Could not load data from the file. Possibly incorrect format.");
                break;
            }//End of if block
            else
            {
                EmployeeNumbers[NextAvailablePosition] = data[0];
                EmployeeNames[NextAvailablePosition] = data[1];
                RegistrationNumbers[NextAvailablePosition] = data[2];
                tval = float.TryParse(data[3], out EngineCapacityArray[NextAvailablePosition]);
                tval = int.TryParse(data[4], out StartKilometresArray[NextAvailablePosition]);
                tval = int.TryParse(data[5], out EndKilometresArray[NextAvailablePosition]);
                TripDescriptions[NextAvailablePosition] = data[6];
                tval = bool.TryParse(data[7], out PassengerCarriedArray[NextAvailablePosition]);

                CurrentRecord = NextAvailablePosition;
                NextAvailablePosition++;
                RecordCount++;                    
             } //End of else block
            } //End of for loop
           Console.WriteLine("Your file is sucessfully loaded.");
   } //End of function