Search code examples
c#textboxtext-files

How to create a .txt file using c#?


I have a window which has two textboxes namely Username and Password and two buttons namely Save and Close. I want to create a .txt file when the save button is clicked.The name of the text file should be the Username and have details of username and password in it. So every time when I save with a different Username it creates a text file with the username as file name.

string fileName = textBox1.Text + ".txt";
File.Create("C:\\Users\\User\\Documents\\1ClickData\\ID\\fileName.txt");

The above code is not working for me. Please help.

Also the textboxes are transparent. I don't want them to be transparent. Please help me out in this also. Thank you.


Solution

  • Try this, if you want to save username password in the same file

    string fileName = textBox1.Text + ".txt"; 
    System.IO.File.WriteAllText(@"C:\\Users\\User\\Documents\\1ClickData\\ID\\" + fileName, "Username="+textBox1.Text+" Password="+textBox2.Text);
    

    or if you want to save username and password in separate file

        //for username
        string fileName1 = textBox1.Text + ".txt"; 
        System.IO.File.WriteAllText(@"C:\\Users\\User\\Documents\\1ClickData\\ID\\" + fileName1, textBox1.Text);
    
        //for password
        string fileName2 = textBox2.Text + ".txt"; 
        System.IO.File.WriteAllText(@"C:\\Users\\User\\Documents\\1ClickData\\ID\\" + fileName2, textBox2.Text);