简体   繁体   中英

Changing a text in a Text file with C#

in my program, user names and passwords are coming from text files. I want to update the password by pressing a button when necessary, what can I do for this?

在此处输入图像描述

 private void Form1_Load(object sender, EventArgs e)
    {

        this.IsMdiContainer = true;

        string[] firmalar = System.IO.File.ReadAllLines(@"Data\\sirket.txt", System.Text.Encoding.GetEncoding("UTF-8"));
        foreach (string str in firmalar)
        {
            SirketList.Items.Add(str);
        }

        string[] kullanici = System.IO.File.ReadAllLines(@"Data\\kullanici.txt", System.Text.Encoding.GetEncoding("UTF-8"));
        foreach (string str in kullanici)
        {
            KullaniciList.Items.Add(str);
        }

        string[] kod = System.IO.File.ReadAllLines(@"Data\\kod.txt", System.Text.Encoding.GetEncoding("UTF-8"));
        foreach (string str in kod)
        {
            kodList.Items.Add(str);
        }
        string[] sistem = System.IO.File.ReadAllLines(@"Data\\sistem.txt", System.Text.Encoding.GetEncoding("UTF-8"));
        foreach (string str in sistem)
        {
            sistemList.Items.Add(str);
        }
        string[] isveren = System.IO.File.ReadAllLines(@"Data\\isveren.txt", System.Text.Encoding.GetEncoding("UTF-8"));
        foreach (string str in isveren)
        {
            isverenList.Items.Add(str);
        }
        string[] araci = System.IO.File.ReadAllLines(@"Data\\araci.txt", System.Text.Encoding.GetEncoding("UTF-8"));
        foreach (string str in araci)
        {
            ListAraci.Items.Add(str);
        }
    }

File static class is your friend here.

Seems you use different files for each one of the properties you want to load/save, so you should bind to your save button code that looks like this:

public static async Task SavePasswordAsync()
{
    await File.WriteAllTextAsync(kodList, text);
}

If I were you, I would store all this information in a single file. And the data would be located line by line. Then I would read it by dividing it by lines as I read, change the new value and rewrite it

Thank you all. This is how I solved it.

string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);

In my code it is like this

String strFile = File.ReadAllText(@"Data\\sistem.txt");

strFile = strFile.Replace(SifreDegistirSistem.Text, newPass.Text);

File.WriteAllText(@"Data\\sistem.txt", strFile);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM