2010-12-02 111 views
1

我有一个包含48行整数的CSV文件。我使用visual c#的openfiledialog功能来允许用户选择这个文件。然后我想让程序将该文件截断为24行。是否有一个截断函数可以用来轻松地完成这项工作?如果不是,我该怎么做呢?下面是我迄今为止...C#截断CSV文件#

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. 
     } 

    } 
} 
+0

+1好问题,因为我发现/获悉,为Linq的`Take`方法的使用。 – 2010-12-02 18:27:06

回答

1
  • 呼叫ReadAllLines获得48个字符串数组
  • 创建的24串
  • 使用Array.Copy一个新的阵列复制你想要的字符串
  • 呼叫WriteAllLines到新数组写入文件

(你也可以使用LINQ的Take法)

+0

+1这是我自己会经历的算法。 – 2010-12-02 18:23:49

5

这可能是一样容易:

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

+1它几乎与1,2,3一样简单! = P – 2010-12-02 18:26:24