从C#中的文本文件读取#
问题描述:
我有以下程序将发送(输出)信息到文本文件,但现在我想从文本文件中读取(输入)。任何建议将不胜感激。我已经评论了几个“我认为”我需要做的事情;但我不确定如何继续。从C#中的文本文件读取#
using System.Windows.Forms;
using System.IO;
namespace Input_Output
{
public partial class Grades : Form
{
private StreamWriter output;
private StreamReader input;
public Grades()
{
InitializeComponent();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void btnCreate_Click(object sender, EventArgs e)
{
btnEnter.Visible = true;
btnClose.Visible = true;
txtFirst.Visible = true;
txtLast.Visible = true;
lblFirst.Visible = true;
lblLast.Visible = true;
listBox1.Visible = true;
lblStatus.Visible = true;
lblGrade.Visible = true;
lblCourse.Visible = true;
cmbID.Visible = true;
lblID.Visible = true;
txtCourse.Visible = true;
txtGrade.Visible = true;
lblStatus.Visible = true;
DialogResult result;
string fileName;
using (SaveFileDialog chooser = new SaveFileDialog())
{
result = chooser.ShowDialog();
fileName = chooser.FileName;
}
output = new StreamWriter(fileName);
btnCreate.Enabled = false;
txtFirst.Visible = true;
txtLast.Visible = true;
lblFirst.Visible = true;
lblLast.Visible = true;
btnEnter.Visible = true;
btnClose.Visible = true;
}
private void btnClose_Click(object sender, EventArgs e)
{
//Close button pushes information from the listbox in to the text file
output.Close();
lblStatus.ForeColor = Color.Red;
lblStatus.Text = "Output File";
btnCreate.Enabled = true;
listBox1.Items.Clear();
cmbID.Text = "";
}
private void btnEnter_Click(object sender, EventArgs e)
{
// Enter button sends information to the list box, a Message Box prompts user to check for accuracy.
//Close button pushes information to the Text file.
string last = "";
string first = "";
string course = "";
string grade = "";
if (txtFirst.Text != "" && txtLast.Text != "" && txtCourse.Text != "")
{
last = txtFirst.Text;
first = txtLast.Text;
course = txtCourse.Text;
grade = txtGrade.Text;
output.WriteLine (last + "\t"+ "\t" + first + ":"+ "\t" + cmbID.SelectedItem + "_" + course + "_" + grade);
listBox1.Items.Add(txtLast.Text + "," + txtFirst.Text + ":" + cmbID.SelectedItem + "-" + txtCourse.Text + "-" + txtGrade.Text);
lblStatus.ForeColor = Color.Navy;
lblStatus.Text = "Entry Saved";
txtFirst.Text = "";
txtLast.Text = "";
txtCourse.Text = "";
txtGrade.Text = "";
txtFirst.Focus();
}
else
{
lblStatus.ForeColor = Color.Red;
lblStatus.Text = "Empty text box or boxes";
}
MessageBox.Show("Please verify that the information is correct before proceeding");
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Grades_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result;
string fileName;
using (OpenFileDialog chooser = new OpenFileDialog())
{
result = chooser.ShowDialog();
fileName = chooser.FileName;
}
//while loop?
//if variable is null, it's the end of the record
//variable= !null
//txt read int variable TxtFile.Text += Rec + "\r\n"; while rec !=null;
}
}
}
答
试试这个:
if(result == DialogResult.OK && fileName != null)
{
try
{
var fileText=File.ReadAllText(fileName);
}
catch(Exception ex)
{
//Handle exception here
}
}
它会读取从选定文件中的所有数据到fileText
变量。
答
读取文本在同一时间,你可以做这样的文件中的一行:
using System.IO;
using (var reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// Do stuff with your line here, it will be called for each
// line of text in your file.
}
}
还有其他的方法为好。例如,如果文件不是太大,你只是想一切都读一个字符串,你可以使用File.ReadAllText()
myTextBox.Text = File.ReadAllText(fileName);
答
检查这个代码:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myStream As Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
'openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 1
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
dataFile = openFileDialog1.FileName
Label1.Text = openFileDialog1.SafeFileName
Dim myReader As New StreamReader(dataFile)
Dim line As String
line = myReader.ReadLine()
While Not (line Is Nothing)
Dim str() As String = Split(line, ControlChars.Tab)
ListView1.Items.Add(New ListViewItem(str))
line = myReader.ReadLine()
End While
myReader.Close()
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub
答
它的代码只需一行:
string content = System.IO.File.ReadAllText(@"C:\textfile.txt");
答
采用分体式(),如在下面
代码
答
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 part_B_19
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
StreamReader sr = new StreamReader(@"C:\Users\Acer\Documents\Visual Studio 2012\Projects\combobox.txt");
string line = sr.ReadLine();
while (line != null)
{
comboBox1.Items.Add(line);
line = sr.ReadLine();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
答
样本程序演示文件I/O在C#
class Items
{
public int itemID { get; set; }
public string itemName { get; set; }
public int itemNo { get; set; }
public string pkgdate { get; set; }
}
class Program
{
private static string connectionString = "...";
static void Main(string[] args)
{
string streadpath = @"I:\itemdata.txt";
string stwritepath = @"I:\itemdata1.txt";
string stcopypath = @"I:\itemdata2.txt";
List<Items> li_all = new List<Items>();
List<Items> li_db = new List<Items>();
List<Items> li_valid = new List<Items>();
List<Items> li_invalid = new List<Items>();
li_all = stread_file(streadpath);
li_invalid = validate(li_all);
li_db = retrievefromDB();
bool x = stwrite_invalid(li_db, stwritepath);
bool y = stcopy_file(streadpath, stcopypath);
}
static List<Items> stread_file(string stpath)
{
List<Items> stli = new List<Items>();
using (StreamReader SR = new StreamReader(stpath))
{
string line = "";
while ((line = SR.ReadLine()) != null)
{
string[] linevalues = line.Split(',');
Items obj = new Items();
obj.itemID = int.Parse(linevalues[0]);
obj.itemName = linevalues[1];
obj.itemNo = int.Parse(linevalues[2]);
obj.pkgdate = linevalues[3];
stli.Add(obj);
}
}
return stli;
}
static List<Items> validate(List<Items> stli)
{
List<Items> li_valid = new List<Items>();
List<Items> li_invalid = new List<Items>();
DateTime parsed;
foreach (Items stit in stli)
{
if(DateTime.TryParseExact(stit.pkgdate, "MM/dd/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out parsed))
{
li_valid.Add(stit);
}
else
{
li_invalid.Add(stit);
}
}
InsertDataToDb(li_valid);
return li_invalid;
}
static bool stwrite_invalid(List<Items> stli,string stpath)
{
using (StreamWriter SW = new StreamWriter(stpath))
{
foreach(Items stit in stli)
{
SW.WriteLine(stit.itemID + "," + stit.itemName + "," + stit.itemNo + "," + stit.pkgdate);
}
}
return true;
}
static bool stcopy_file(string stsourcepath, string stdestinationpath)
{
File.Copy(stsourcepath, stdestinationpath);
return true;
}
static void InsertDataToDb(List<Items> stli)
{
var records = stli;
using (SqlConnection con = new SqlConnection(connectionString))
{
StringBuilder nonQuery = new StringBuilder();
foreach (var item in records)
{
nonQuery.AppendFormat("INSERT INTO dbo.Smartphone VALUES ({0}, '{1}', {2}, '{3}');",
item.itemID,
item.itemName,
item.itemNo,
item.pkgdate);
}
SqlCommand cmd = new SqlCommand(nonQuery.ToString(),con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
static List<Items> retrievefromDB()
{
List<Items> stli = new List<Items>();
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from dbo.Smartphone", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Items obj = new Items();
obj.itemID = (int)dt.Rows[i]["ID"];
obj.itemName = dt.Rows[i]["Name"].ToString();
obj.itemNo = (int)dt.Rows[i]["Num"];
obj.pkgdate = dt.Rows[i]["RDate"].ToString();
stli.Add(obj);
}
}
return stli;
}
}