覆盖.txt文件

时间:2018-02-02 15:21:13

标签: c# visual-studio-2015

我有一个测试应用程序,它从用户获取信息并将其保存到文本文件中。问题出现在需要在列表结构中插入某些信息的位置,即使用户将在文档中稍后遇到相应的字段。

enter image description here

我已决定采用惰性路径并将占位符放在稍后我需要在文本文件中添加的信息中,但我不知道如何有选择地覆盖行。

以下是示例:

表格1:

enter image description here

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();
        }}}

表格2:

enter image description here

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();
    }}}

1 个答案:

答案 0 :(得分:0)

如果您想查找特定行并重新编写该行,您可以执行以下操作:

        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);