How to parse a text file with C#

后端 未结 7 1926
面向向阳花
面向向阳花 2020-12-08 14:57

By text formatting I meant something more complicated.

At first I began manually adding the 5000 lines from the text file I\'m asking this question for,into my proje

7条回答
  •  青春惊慌失措
    2020-12-08 15:15

    One way that I've found really useful in situations like this is to go old-school and use the Jet OLEDB provider, together with a schema.ini file to read large tab-delimited files in using ADO.Net. Obviously, this method is really only useful if you know the format of the file to be imported.

    public void ImportCsvFile(string filename)
    {
        FileInfo file = new FileInfo(filename);
    
        using (OleDbConnection con = 
                new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
                file.DirectoryName + "\";
                Extended Properties='text;HDR=Yes;FMT=TabDelimited';"))
        {
            using (OleDbCommand cmd = new OleDbCommand(string.Format
                                      ("SELECT * FROM [{0}]", file.Name), con))
            {
                con.Open();
    
                // Using a DataReader to process the data
                using (OleDbDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        // Process the current reader entry...
                    }
                }
    
                // Using a DataTable to process the data
                using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
                {
                    DataTable tbl = new DataTable("MyTable");
                    adp.Fill(tbl);
    
                    foreach (DataRow row in tbl.Rows)
                    {
                        // Process the current row...
                    }
                }
            }
        }
    } 
    

    Once you have the data in a nice format like a datatable, filtering out the data you need becomes pretty trivial.

提交回复
热议问题