Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
889 views
in Technique[技术] by (71.8m points)

csv - C# and CsvHelper - How to open file, modify values and re-write the file

How can I open a simple 2 line CSV (first line header of 15+ fields, second line data values) using CSVHelper to then modify just some of the values (field 3, 9, 12 for example) and then re-write the file of all 15+ fields

I've created a simple class

    public class InputFileData
    {
        // Match the existing file structure
        public string supplierID { get; set; }
        public string barcode { get; set; }
        public string invoiceNumber { get; set; }
        public string totalCost { get; set; }
        ......rest of fields
    }

I have got as far as being able to read in the header to this class and second line of text but cannot get the syntax right for:

  1. Changing specific field values to something new i.e., field[3].text = newvalue
  2. Using the csvWriter part to re-write the values.

I've read up the sample help etc but cannot reference the data being read in correctly.

This works so far - you can see where the changing value / writing to file question comes up . private void button1_Click(object sender, EventArgs e) {

        inputfileDialog.ShowDialog();

        txtInputFilepath.Text = inputfileDialog.FileName;

        using (var reader = new StreamReader(txtInputFilepath.Text))

        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            // Correctly opens and reads in the header

            var records = csv.GetRecords<InputFileData>();
            
            foreach (var lineOfText in records)
            {
                // Loads up the content on screen so i can see the valus
                txtFileContents.AppendText(lineOfText.authcode_auto + "," + lineOfText.barcode_auto + "," + lineOfText.tagdata_auto + "," + Environment.NewLine);
                
            }

        }

// WRITING BIT

        using (var writer = new StreamWriter("C:\Users\Public\Output2.txt"))

        using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))

        {
            csv.WriteHeader<InputFileData>(); //Correctly writes the header back to the new file
            csv.NextRecord();

            // WHAT TO PUT HERE???
        }

}

question from:https://stackoverflow.com/questions/65936089/c-sharp-and-csvhelper-how-to-open-file-modify-values-and-re-write-the-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following code works - I'm not sure it's that efficient or correct to be using a seperate list object alongside the record-set IEnumerable but needs must here.... It does ensure regardless of length of file only one row of data is written back which was also needed

private void button1_Click(object sender, EventArgs e)
    {
        var recordList = new List<InputFileData> { };
        int i = 0;

        inputfileDialog.ShowDialog();

        txtInputFilepath.Text = inputfileDialog.FileName;

        using (var reader = new StreamReader(txtInputFilepath.Text))

        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))

        {
            recordSet = csv.GetRecords<InputFileData>();

            foreach (var lineOfText in recordSet)
            {
                txtFileContents.AppendText(lineOfText.authcode_auto + "," + lineOfText.barcode + "," + lineOfText.tagdata + "," + Environment.NewLine);
            
                if (i < 1) { recordList.Add(lineOfText); }; // Reduce text file importing to header and first line of data only
                                                            // Add line to record list 
                i++;
            }
        }

        using (StreamWriter writer = new StreamWriter("C:\Users\Public\Output2.txt"))

        using (var csvOut = new CsvWriter(writer, CultureInfo.InvariantCulture))

        {
            
        csvOut.WriteHeader<InputFileData>(); //Correctly writes the header back to the new file
        csvOut.NextRecord();

        recordList[0].barcode = "TestTestTest";
        recordList[0].suppID = "Test2Test2Test2";

        csvOut.WriteRecords(recordList);
        }

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...