C# 读取文件并显示内容
我希望当我单击“列出所有客户”按钮时,代码应该读取Customer.csv文件,并在名为“列出所有客户”的表单上显示信息 我该怎么做C# 读取文件并显示内容,c#,file-io,C#,File Io,我希望当我单击“列出所有客户”按钮时,代码应该读取Customer.csv文件,并在名为“列出所有客户”的表单上显示信息 我该怎么做 public static void ReadFile() { StreamReader sr = File.OpenText("Customer.csv"); } public static void LoadCustomers() { try { if (File.Exists("Customer.csv"))
public static void ReadFile()
{
StreamReader sr = File.OpenText("Customer.csv");
}
public static void LoadCustomers()
{
try
{
if (File.Exists("Customer.csv"))
{
string temp = null;
int count = 0;
using (StreamReader sr = File.OpenText(@"Customer.csv"))
{
while ((temp = sr.ReadLine()) != null)
{
temp = temp.Trim();
string[] lineHolder = temp.Split(',');
Customer tempCust = new Customer();
tempCust.customerName = lineHolder[0];
tempCust.customerAddress = lineHolder[1];
tempCust.customerZip = Convert.ToInt32(lineHolder[2]);
myCustArray[count] = tempCust;
count++;
}//end for loop
}
}
else
{
File.Create("Customer.csv");
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("File Loading Error: " + e.Message);
}
}
我不确定您希望在哪种控件中显示这些数据,但您的方法可以只返回一个客户列表,然后您可以添加到ListBox、ListView或DataGrid
首先,利用列表对象:
public static void ReadFile()
{
StreamReader sr = File.OpenText("Customer.csv");
}
public static void LoadCustomers()
{
try
{
if (File.Exists("Customer.csv"))
{
string temp = null;
var retList = new List<Customer>();
using (StreamReader sr = File.OpenText(@"Customer.csv"))
{
while ((temp = sr.ReadLine()) != null)
{
temp = temp.Trim();
string[] lineHolder = temp.Split(',');
retlist.add(new Customer(){
customerName = linerHolder[0],
customerAddress = lineHolder[1],
customerZip = Convert.ToInt32(lineHolder[2])
});
}//end for loop
}
}
else
{
File.Create("Customer.csv");
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("File Loading Error: " + e.Message);
}
}
只需将其封装在一个类中,从控制器调用if并填充结果。根据您更新此数据的频率,您可以研究缓存它,这样就不必为每个用户每X秒运行一次此过程
listBox1.DisplayMember = "customerName";
listBox1.Items.AddRange(LoadCustomers(@"G:\Customers.csv").ToArray());
public static void ReadFile()
{
StreamReader sr = File.OpenText("Customer.csv");
}
public static void LoadCustomers()
{
try
{
if (File.Exists("Customer.csv"))
{
string temp = null;
var retList = new List<Customer>();
using (StreamReader sr = File.OpenText(@"Customer.csv"))
{
while ((temp = sr.ReadLine()) != null)
{
temp = temp.Trim();
string[] lineHolder = temp.Split(',');
retlist.add(new Customer(){
customerName = linerHolder[0],
customerAddress = lineHolder[1],
customerZip = Convert.ToInt32(lineHolder[2])
});
}//end for loop
}
}
else
{
File.Create("Customer.csv");
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("File Loading Error: " + e.Message);
}
}