如何在C#中读取和删除文本? [英] How do I read and delete from text in C#?
问题描述
我已经阅读了我的编程书,并看到了在线示例,尽管如此,我似乎无法让它工作。我可以从列表框中删除,但它不会从实际的txt文件中删除它。此外,它根本不会读。
我尝试过:
I've read my programming book, and seen online examples, nonetheless, I can not seem to get it to work. I can delete from the list box fine, but it will not delete it from the actual txt file. Furthermore, it will not read at all.
What I have tried:
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 TripCostCalculator
{
public partial class Form1 : Form
{
private const string dir = @"C:\C# 2015\Files\";
private const string path = dir + "PayCheckCalculator.txt";
decimal tax = .06m;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
StreamReader textIn =
new StreamReader(
new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));
textIn.Close();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
string name = txtName.Text;
decimal dph;
decimal grossIncome;
decimal netIncome;
if (!decimal.TryParse(txtDph.Text, out dph))
{
MessageBox.Show("Please enter a valid dollar amount");
return;
}
decimal hoursWorked;
if (!decimal.TryParse(txtHoursWorked.Text, out hoursWorked))
{
MessageBox.Show("Please enter a valid dollar amount");
return;
}
grossIncome = dph * hoursWorked;
txtGrossIncome.Text = grossIncome.ToString("c");
netIncome = grossIncome - (grossIncome * tax);
txtNetIncome.Text = netIncome.ToString("c");
}
private void btnDelete_Click(object sender, EventArgs e)
{
for (int v = 0; v < lstSalary.SelectedItems.Count; v++)
{
lstSalary.Items.Remove(lstSalary.SelectedItems[v]);
}
if (System.IO.File.Exists(@"C:\C# 2015\Files\"))
{
System.IO.File.Delete("PayCheckCalculator.txt");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnAdd_Click(object sender, EventArgs e)
{
lstSalary.Items.Add(txtName.Text);
lstSalary.Items.Add(txtDph.Text);
lstSalary.Items.Add(txtHoursWorked.Text);
lstSalary.Items.Add(txtGrossIncome.Text);
lstSalary.Items.Add(txtNetIncome.Text);
}
private void btnSave_Click_1(object sender, EventArgs e)
{
StreamWriter textOut = new StreamWriter(
new FileStream(path, FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write));
textOut.Write(txtName.Text + ",");
textOut.Write(txtDph.Text + ",");
textOut.Write(txtHoursWorked.Text + ",");
textOut.Write(txtGrossIncome + ",");
textOut.Write(txtNetIncome.Text + ",");
textOut.Close();
txtName.Clear();
txtDph.Clear();
txtHoursWorked.Clear();
txtGrossIncome.Clear();
txtNetIncome.Clear();
}
}
}
推荐答案
附加到文本文件很容易;通过删除任意部分来更新文件将是一团糟。这就是数据库的用途,或者使用序列化/反序列化。
虽然有些人试图使文本文件成为一种随机访问数据库,imho,那是浪费时间,它还要求您处理文本编码,行尾字符的问题,并且文本文件的每个虚拟记录部分具有相同的长度或系统地用开始/结束分隔符括起来。请不要去那里!
在Form.Load事件中发生了什么,你创建一个新的StreamReader,打开和关闭一个文件,但是你做了没有读取文件,或者保持对Stream的引用?如果这只是为了确保文件存在,那么为什么不先检查它是否存在?
Appending to a text file is easy; updating the file by deleting arbitrary sections is going to be a mess. That's what databases are for, or using serialization/deserialization is for.
While some folks attempt to make a text file a kind of random-access database, imho, that's a waste of time, and it also requires that you deal with issues of text-encoding, line-end characters, and that each "virtual record" section of the text file have identical length or be bracketed systematically with start/end delimiters. Please, don't go there !
What's going on in the Form.Load event where you create a new StreamReader, and open and close a file, but you do not read the file, or, keep a reference to the Stream ? If that's just to make sure the file exists, then why not check if it exists first ?
private void Form1_Load(object sender, EventArgs e)
{
if (! File.Exists(path))
{
using (FileStream fs = File.Create(path)){}
}
}
你的代码没有读取,因为......好吧......你没有调用任何代码......我可以看到......读取文件?
想一想:
a。使用数据库,加上绑定到它的一些适当的UI控件(DataGridView?)
......或者......
b.1使用类EmployeePayRecord为员工记录建模
b.2创建EmployeePayRecord实例的集合等级。
c。使用非常方便和强大的WCF序列化工具,根据需要将集合保存到文件中,或者重新读取。
如果你真的不想使用一个数据库,看看这篇文章使用XML作为一个简单的数据存储与通常的CRUD工具:[ ^ ]。
Your code is not reading because ... well ... you are not calling any code ... that I can see ... to read the file ?
Think about:
a. use a database, coupled with some appropriate UI control bound to it (DataGridView ?)
... or ...
b.1 model the employee "record" with a Class, "EmployeePayRecord"
b.2 create a collection of instances of the "EmployeePayRecord" Class.
c. use the very convenient and powerful WCF serialization tools to save the collection to a file as needed, or read it back in.
If you really don't want to use a database, check out this article that uses XML as a simple "data store" with the usual CRUD facilities: [^].
这篇关于如何在C#中读取和删除文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!