简体   繁体   English

将文本保存在文件中而不删除 windows 形式 c#

[英]Save text in a file without deleting in windows form c#

I was creating a program in Windows forms and I wanted to save the username and the password in 2 separate files.我正在 Windows forms 中创建一个程序,我想将用户名和密码保存在 2 个单独的文件中。 One is named: name .一个被命名为: name The second is named: password .第二个被命名为: 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.假设我在重新启动程序时将 Carl 插入姓名,将 Jones 插入姓氏,我希望在第一个文件中的名称和第二个中的姓氏文件中不删除任何内容。 Thanks!谢谢!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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