I have an test application that takes information from a user and saves it onto a text file. The problem arises to where certain information needs to be inserted within the structure of the list even though the user will encounter the appropriate fields much later on in the document.
I have decided to go the lazy route and put placeholders for the information I need added in the text file later on, but I have no idea how to selectively overwrite lines.
Here is the example:
Form 1:
using System.IO;
namespace Debug.NewFolder1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnNextInfo_Click_1(object sender, EventArgs e)
{
System.IO.StreamWriter objwriter;
objwriter = new System.IO.StreamWriter("Info.txt", true);
objwriter.Write("nameL=" + tbxLast.Text);
objwriter.WriteLine();
objwriter.Write("nameF=" + tbxFirst.Text);
objwriter.WriteLine();
objwriter.Write("nameM=" + tbxMiddle.Text);
objwriter.WriteLine();
objwriter.Write("numberAge=" + tbxAge.Text);
objwriter.WriteLine();
//Occupation
objwriter.Write("Occupation=");
objwriter.WriteLine();
//Certification
objwriter.Write("Certification=");
objwriter.WriteLine();
objwriter.Write("Residence=" + tbxRes.Text);
objwriter.WriteLine();
objwriter.Close();
NewFolder1.Form2 settingsForm = new NewFolder1.Form2();
settingsForm.Show();
this.Hide();
}}}
Form 2:
using System.IO;
namespace Debug.NewFolder1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btnNextInfo_Click(object sender, EventArgs e)
{
System.IO.StreamWriter objwriter;
objwriter = new System.IO.StreamWriter("Info.txt", true);
//skip 4 lines
objwriter.Write("Occupation=" + tbxOcc.Text);
objwriter.WriteLine();
objwriter.Write("Certification=" + tbxCert.Text);
objwriter.WriteLine();
//skip 1 line
objwriter.Close();
Application.Exit();
}}}
If you want to look up a specific line and re-write just that line you can do something like this:
string filePath = ""; //Your file path goes here
string[] lines = File.ReadAllLines(filePath);
string newLastName = "Smith";
string newFirstName = "John";
for (int i = 0; i < lines.Count(); i++)
{
if (lines[i].Contains("nameL="))
lines[i] = "nameL=" + newLastName;
if (lines[i].Contains("nameF="))
lines[i] = "nameF=" + newFirstName;
}
File.WriteAllLines(filePath, lines);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.