开发者

Truncate CSV file in C#

I have a CSV file with 48 rows of integers. I am using the openfiledialog feature of visual c# to allow a user to select this file. I then want to have the program truncate that file down to 24 rows. Is there a truncate function I can use to do this easily? If not how can I go about doing so? Below is what I have so far...

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace sts_converter
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            Initial开发者_如何学GoizeComponent();
        }

        private void select_Click(object sender, EventArgs e)
        {
            int size = -1;
            DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
            if (result == DialogResult.OK) // Test result.
            {
                string file = openFileDialog1.FileName;
                try
                {
                    string text = File.ReadAllText(file);
                    size = text.Length;
                }
                catch (IOException)
                {
                }
            }
            Console.WriteLine(size); // <-- Shows file size in debugging mode.
            Console.WriteLine(result); // <-- For debugging use only.
        }

    }
}


It could be as easy as:

string file = openFileDialog1.FileName;
File.WriteAllLines(
    file, 
    File.ReadLines(file).Take(28).ToArray()
);


  • Call ReadAllLines to get an array of 48 strings
  • Create a new array of 24 strings
  • Use Array.Copy to copy the strings that you want
  • Call WriteAllLines to write the new array to the file

(You can also use LINQ's Take method)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜