简体   繁体   English

在C#中截断CSV文件

[英]Truncate CSV file in C#

I have a CSV file with 48 rows of integers. 我有一个包含48行整数的CSV文件。 I am using the openfiledialog feature of visual c# to allow a user to select this file. 我正在使用Visual C#的openfiledialog功能,以允许用户选择此文件。 I then want to have the program truncate that file down to 24 rows. 然后,我想让程序将文件截断为24行。 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()
        {
            InitializeComponent();
        }

        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 调用ReadAllLines以获取48个字符串的数组
  • Create a new array of 24 strings 创建一个包含24个字符串的新数组
  • Use Array.Copy to copy the strings that you want 使用Array.Copy复制所需的字符串
  • Call WriteAllLines to write the new array to the file 调用WriteAllLines将新数组写入文件

(You can also use LINQ's Take method) (您也可以使用LINQ的Take方法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM