C#读取文本文件并打印到表中

时间:2015-11-13 14:08:25

标签: c# file-io

我正在尝试阅读文本文件并打印到表格中。 我希望输出是这个

enter image description here

但现在我有不同的输出

enter image description here

var column1 = new List<string>();
var column2 = new List<string>();
var column3 = new List<string>();

using (var rd = new StreamReader(@"C:\test.txt"))
{
    while (!rd.EndOfStream)
    {
          var splits = rd.ReadLine().Split(';');
          column1.Add(splits[0]);
          column2.Add(splits[1]);
          column3.Add(splits[2]);
    }
}

Console.WriteLine("Date/Time \t Movie \t Seat");
foreach (var element in column1) Console.WriteLine(element); 
foreach (var element in column2) Console.WriteLine(element);
foreach (var element in column3) Console.WriteLine(element);

3 个答案:

答案 0 :(得分:1)

您可以使用 Linq 构建一个方便的结构(例如List<String[]>),然后打印出所需的所有数据:

List<String[]> data = File
  .ReadLines(@"C:\test.txt")
 //.Skip(1) // <- uncomment this to skip caption if the csv has it
  .Select(line => line.Split(';').Take(3).ToArray()) // 3 items only
  .ToList();

// Table output (wanted one):
String report = String.Join(Environment.NewLine, 
  data.Select(items => String.Join("\t", items)));   

Console.WriteLine(report);

// Column after column output (actual one)
Console.WriteLine(String.Join(Environment.NewLine, data.Select(item => item[0])));
Console.WriteLine(String.Join(Environment.NewLine, data.Select(item => item[1])));
Console.WriteLine(String.Join(Environment.NewLine, data.Select(item => item[2])));

编辑:如果您想选择电影购票等,请详细说明结构:

  // Create a custom class where implement your logic 
  public class MovieRecord {
    private Date m_Start;
    private String m_Name;
    private int m_Seats;

    ... 
    public MovieRecord(DateTime start, String name, int seats) {
      ...
      m_Seats = seats;
      ...
    }
    ...

    public String ToString() {
      return String.Join("\t", m_Start, m_Name, m_Seats);
    }

    public void Buy() {...}
    ...
  }

然后转换为 conventinal structure

  List<MovieRecord> data = File
    .ReadLines(@"C:\test.txt")
    //.Skip(1) // <- uncomment this to skip caption if the csv has it
    .Select(line => {
       String items[] = line.Split(';'); 
       return new MovieRecord(
         DateTime.ParseExact(items[0], "PutActualFormat", CultureInfo.InvariantCulture), 
         items[1], 
         int.Parse(items[2]));
    }
    .ToList();

表输出将是

  Console.Write(String.Join(Envrironment.NewLine, data));

答案 1 :(得分:0)

如果要添加“列”,请不要使用Console.WriteLine。您还应该使用一个List<string[]>而不是多个List<string>

List<string[]> allLineFields = new List<string[]>();
using (var rd = new StreamReader(@"C:\test.txt"))
{
    while (!rd.EndOfStream)
    {
        var splits = rd.ReadLine().Split(';');
        allLineFields.Add(splits);
    }
}

Console.WriteLine("Date/Time \t Movie \t Seat");
foreach(string[] line in allLineFields)
    Console.WriteLine(String.Join("\t", line)); 

一般情况下,如果要解析csv文件,而不是字符串方法或正则表达式,则应使用真正的csv解析器。

您可以直接使用框架中唯一可用的TextFieldParser

var allLineFields = new List<string[]>();
using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(@"C:\test.txt"))
{
    parser.Delimiters = new string[] { ";" };
    parser.HasFieldsEnclosedInQuotes = false; // very useful 
    string[] lineFields;
    while ((lineFields = parser.ReadFields()) != null)
    {
        allLineFields.Add(lineFields);
    }
}

您需要在项目中添加对Microsoft.VisualBasic dll的引用。

还有其他可用的内容:Parsing CSV files in C#, with header

答案 2 :(得分:0)

您可以尝试以更加面向对象的方式解决此问题,这可能会使您更容易使用:

您可以声明一个简单的类来表示电影席位:

class MovieSeat
{
    public readonly string Date, Name, Number;

    public MovieSeat(string source)
    {
        string[] data = source.Split(';');
        Date = data[0];
        Name = data[1];
        Number = data[2];
    }
}

然后您可以通过几行代码读入并打印出数据:

// Read in the text file and create a new MovieSeat object for each line in the file.
// Iterate over all MovieSeat objets and print them to console.
foreach(var seat in File.ReadAllLines(@"C:\test.txt").Select(x => new MovieSeat(x)))
    Console.WriteLine(string.Join("\t", seat.Date, seat.Name, seat.Number));