簡體   English   中英

需要幫助閱讀C#文件中的子字符串嗎?

[英]Need help reading Substrings in Files in C#?

所以我創建了一個子程序來讀取一些文件...這是代碼:

dataGridView1.Rows.Clear();

            string[] lines = File.ReadAllLines(Application.StartupPath + listBox1.Text + ".txt");

            foreach (string line in lines)
        {

            int posicion1 = line.IndexOf("|") + 1;
            int posicion2 = line.IndexOf("|", posicion1) + 1;
            int posicion3 = line.IndexOf("|", posicion2) + 1;
            int posicion4 = line.IndexOf("|", posicion3) + 1;


            data1 = line.Substring(0, posicion1 - 1);
            data2 = line.Substring(posicion1, posicion2 - posicion1 - 1);
            formacao = line.Substring(posicion2, posicion3 - posicion2 - 1);
            relatorio = line.Substring(posicion3, posicion4 - posicion3 -1);

            dataGridView1.Rows.Add(data1, data2, formacao, relatorio);


        }

但是,在將變量“ relatorio”添加到dataGridView時,它僅添加了將變量保存到的整個行...例如,這就是我從文件中保存一行的方式:

2017年6月28日| 2017年6月28日| fsdfsdfsd |Não

如您所見,我用“ |”分隔所有變量。 總結起來,該程序可以正常運行,只是變量“ relatorio”只是在應添加“Não”時才添加整個行(2017年6月28日的日期| 2017年6月28日的fsdfsdfsd |Não)。

有人可以幫我嗎? 很抱歉,如果這個問題還不夠清楚。

- 更新

所以我試着用這個代替:

 foreach (string line in lines)
        {

            string[] _line = line.Split('|');
            string value1 = _line[0];
            string value2 = _line[1];
            string value3 = _line[2];
            string value4 = _line[3];
            dataGridView1.Rows.Add(value1, value2, value3, value4);


        }

但是仍然我的程序仍然存在相同的錯誤...我開始認為我沒有正確保存文件,但是我真的看不到我搞砸的任何地方...當我關閉文件時,文件保持相同類型該程序:

2017年6月28日| 2017年6月28日| fwfew |Não

如果您有時間,誰能測試一下?

String類已經具有一個Split方法:

var parts=line.Split('|');
dgv1.Rows.Add(parets[0], parts[1], parts[2], parts[3]);

各種Split重載允許您使用多個分隔符並消除空結果

您可能應該看一下CsvHelper之類的解析器。 它可以將CSV數據直接解析並映射到對象,允許自定義映射和轉換,例如:

public class MyClass { public string Data1{get;set;} ...}

using(var reader=File.OpenText(csvPath))
{
    var csv = new CsvReader( textReader );
    csv.Configuration.Delimiter = "|";
    var records = csv.GetRecords<MyClass>().ToList();
    dgv1.DataSource=records;
}

或使用LINQ:

    var records = csv.GetRecords<MyClass>().Where(it=>it.Data1 >=...).ToList();

使用IndexOf ,會使事情比應該的復雜一些。 您可以只使用Split方法獲取值:

foreach (string line in lines)
{
     string[] _line = line.Split('|');
     string value1 = _line[0];
     string value2 = _line[1];
     ...

     dataGridView1.Rows.Add(value1 , value2 , ...);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM