【发布时间】:2016-05-07 19:56:00
【问题描述】:
我有一个 Windows 表单,它使用 StreamReader 将表单数据读入一些文本框。这工作得很好。现在的问题是我想按名称的字母顺序显示文件中的数据。早些时候我尝试了一个 array.Sort 方法,但效果不太好。
这是我的代码:
注意:我在 dispose 方法中关闭了阅读器和文件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ViewArchives
{
public partial class Form1 : Form
{
const char DELIM = ',';
const string FILENAME = @"F:\lscSpring2016\CIS2620\FinalProject\TicketMaster\bin\Debug\SoldTickets.txt";
string recordIn;
string[] fields;
static FileStream file = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(file);
public Form1()
{
InitializeComponent();
}
private void btnView_Click(object sender, EventArgs e)
{
try
{
recordIn = reader.ReadLine();
fields = recordIn.Split(DELIM);
nameBox.Text = fields[0];
ticketsBox.Text = fields[1];
purchaseBox.Text = fields[2];
dateBox.Text = fields[3];
}
catch (NullReferenceException)
{
label5.Text = "You have viewed\nall the records filed.";
btnView.Enabled = false;
}
}
}
}
【问题讨论】:
-
fields = recordIn.Split(DELIM).OrderBy(x=>x).ToArray(); -
通过异常进行流控制并不是很好的设计。您应该检查 ReadLine() 的返回值;如果为 null,则您已到达文件末尾。
-
为什么 Array.Sort() 不起作用?
标签: c# arrays forms streamreader