Reputation: 11
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()
{
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.
}
}
}
Upvotes: 1
Views: 813
Reputation: 1039438
It could be as easy as:
string file = openFileDialog1.FileName;
File.WriteAllLines(
file,
File.ReadLines(file).Take(28).ToArray()
);
Upvotes: 5
Reputation: 888177
ReadAllLines
to get an array of 48 stringsArray.Copy
to copy the strings that you wantWriteAllLines
to write the new array to the file(You can also use LINQ's Take
method)
Upvotes: 1