Search code examples
c#filetextappdata

Writing to a text file in AppData doesn't work - C#


I'm using the following lines of code in order to write credentials of users to a text file. It's supposed to create the directory inside AppData (which it does) but it doesn't write the credentials to the text file, it leaves it blank!

public void RegisterUserCreds()
{
    string[] creds = { Username.Text, Password.Text };
    string roaming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
    if (!Directory.Exists(roaming + "/Launcher")) 
        Directory.CreateDirectory(roaming + "/Launcher");
    string specificFolder = roaming + "/Launcher/user_info.txt";
    var fs = File.Open(specificFolder, FileMode.OpenOrCreate, FileAccess.ReadWrite);
    var sw = new StreamWriter(fs);
    sw.WriteLine(Username.Text);
    fs.Close();
}

What's the problem? Thanks!


Solution

  • Just use the using statement when operating on streams:

    public static void RegisterUserCreds()
    {
        string[] creds = { Username.Text, Password.Text };
        string roaming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
        if (!Directory.Exists(roaming + "/Launcher")) Directory.CreateDirectory(roaming + "/Launcher");
        string specificFolder = roaming + "/Launcher/user_info.txt";
        using (var fs = File.Open(specificFolder, FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            using (var sw = new StreamWriter(fs))
            {
                sw.WriteLine(Username.Text);
            }
        }
    }
    

    In your code you were closing the file stream before the stream writer was able to flush the changes you want to write so the file was created empty.