Home > Back-end >  Save text in a file without deleting in windows form c#
Save text in a file without deleting in windows form c#

Time:08-30

I was creating a program in Windows forms and I wanted to save the username and the password in 2 separate files. One is named: name. The second is named: password. So first I check if the 2 files are empty but when I run the code it deletes the data on the files.

private void btn1_Click(object sender, EventArgs e)
{
    int count = 0;
    TextWriter name = new StreamWriter("C:\\Users\\skerd\\AppData\\Local\\Temp\\jvvhbbcp..txt");
    TextWriter psswd = new StreamWriter("C:\\Users\\skerd\\AppData\\Local\\Temp\\x1pu0bds..txt");

    if (new FileInfo("C:\\Users\\skerd\\AppData\\Local\\Temp\\jvvhbbcp..txt").Length == 0 && new FileInfo("C:\\Users\\skerd\\AppData\\Local\\Temp\\x1pu0bds..txt").Length == 0)
    {
        if (count < 1)
        {
            name.Write(txtB_1.Text);
            psswd.Write(txtB_2.Text);
            name.Close();
            psswd.Close();
            count  ;
        }
        Close();
    }

Let's suppose I insert Carl in the name and Jones in the surname when I restart the program I want that in the files it got in the first one the name and in the second one the surname without deleting anything. Thanks!

CodePudding user response:

You can load your files content or create new content and then modify your content and then - delete original and replace with new. Although, you could, as additional step, first - rename the original as backup and then save the new and then remove the original backup.

    var nameFile = "PATH1";
    var pwdFile = "PATH2";
    bool nameExists = File.Exists(nameFile); 
    bool pwdExists = File.Exists(pwdFile);
    
    StringBuilder nameContent = new StringBuilder();
    if (nameExists)
        nameContent.Append(File.ReadAllText(nameFile));
    
    
    StringBuilder pwdContent = new StringBuilder();
    if (pwdExists) 
        pwdContent.Append(File.ReadAllText(pwdFile));
    

    // you can potencially do more text manipulations here
    
    nameContent.AppendLine("NEW NAME");
    pwdContent.AppendLine("NEW PASSWORD");
    
    if (nameExists)
        File.Delete(nameFile);
    
    File.WriteAllText(nameFile, nameContent.ToString());
    
    
    if (pwdExists)
        File.Delete(pwdFile); 
    
    File.WriteAllText(pwdFile, pwdContent.ToString());
  • Related