0

我正在运行三个计数器,一个返回字符总数,一个返回“|”的数量 我的 .txt 文件中的字符(总计)。还有一个是阅读我的文本文件中有多少单独的行。我假设我的计数器是错误的,我不确定。在我的文本文件中有一些额外的 '|' 字符,但这是我需要稍后修复的错误...

The Message Boxes show  
"Lines = 8"   
"Entries = 8"   
"Total Chars = 0"  

不确定它是否有帮助,但 .txt 文件是使用 streamwriter 编译的,并且我将 datagridview 保存到字符串中以创建输出。这些功能似乎一切正常。

这是我正在阅读的文本文件的副本

Matthew|Walker|MXW320|114282353|True|True|True  
Audrey|Walker|AXW420|114282354|True|True|True    
John|Doe|JXD020|111222333|True|True|False  
||||||  

这是代码。

    private void btnLoadList_Click(object sender, EventArgs e)
    {
        var loadDialog = new OpenFileDialog
            {
                InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments),
                Filter = "Text (*.txt)|*.txt",
                FilterIndex = 1
            };
        if (loadDialog.ShowDialog() != DialogResult.OK) return;
        using (new StreamReader(loadDialog.FileName))
        {
            var lines = File.ReadAllLines(loadDialog.FileName);//Array of all the lines in the text file
            foreach (var assocStringer in lines)//For each assocStringer in lines (Runs 1 cycle for each line in the text file loaded)
            {
                var entries = assocStringer.Split('|'); // split the line into pieces (e.g. an array of "Matthew", "Walker", etc.)
                var obj = (Associate) _bindingSource.AddNew();
                if (obj == null) continue;
                obj.FirstName = entries[0];
                obj.LastName = entries[1];
                obj.AssocId = entries[2];
                obj.AssocRfid = entries[3];
                obj.CanDoDiverts = entries[4];
                obj.CanDoMhe = entries[5];
                obj.CanDoLoading = entries[6];
            } 
      }
   }

希望你们在这里找到错误。抱歉,如果格式草率,我是自学的,不上课。欢迎任何额外的建议,尽可能诚实和严厉,不会伤害任何感情。

总之

为什么这个程序没有从我正在使用的文本文件中读取正确的值?

4

1 回答 1

1

不完全确定我得到了你想要做的事情,所以如果我离开了,请纠正我,但如果你只是想获得文件的行数、管道 (|) 计数和字符计数,以下应该给你。

var lines = File.ReadAllLines(load_dialog.FileName);
int lineCount = lines.Count();
int totalChars = 0;
int totalPipes = 0; // number of "|" chars

foreach (var s in lines)
{
    var entries = s.Split('|');  // split the line into pieces (e.g. an array of "Matthew", "Walker", etc.)
    totalChars += s.Length;   // add the number of chars on this line to the total
    totalPipes = totalPipes + entries.Count() - 1; // there is always one more entry than pipes
}

Split()所做的就是将整行拆分为字符串中各个字段的数组。由于您似乎只关心管道的数量而不是字段,因此除了通过获取字段的数量并减去一个来确定管道的数量(因为您没有尾随管道)之外,我并没有做太多的事情在每一行)。

于 2012-12-13T03:06:44.803 回答