在 C# 中截断 CSV 文件
我有一个包含 48 行整数的 CSV 文件。我正在使用 Visual C# 的 openfiledialog 功能来允许用户选择此文件。然后我想让程序将该文件截断为 24 行。是否有一个截断函数可以用来轻松完成此操作?如果不是,我该如何去做呢?以下是我到目前为止所拥有的......
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.
}
}
}
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.
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它可能很简单:
It could be as easy as:
ReadAllLines
获取 48 个字符串的数组Array.Copy
复制所需的字符串WriteAllLines
将新数组写入文件(您也可以使用 LINQ 的
Take
方法)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)