3

After the user logins in the program, I want that my program remembers the username of the last user and when the program reopens, the username filed is filled automatically with the username of that last user.

I want to know how to save and restore username. I dont want to use a database.

Adrian Toman
  • 11,316
  • 5
  • 48
  • 62
Iman
  • 533
  • 2
  • 8
  • 23
  • Check out http://stackoverflow.com/questions/3032492/save-settings-in-a-net-winforms-application – Farray Jun 18 '11 at 20:34
  • possible duplicate of [What is the best way to store user settings for a .NET application?](http://stackoverflow.com/questions/26369/what-is-the-best-way-to-store-user-settings-for-a-net-application) – Merlyn Morgan-Graham Jun 18 '11 at 20:38

2 Answers2

10

A better solution than temporary files is simply to use application settings.

To set the last username:

Properties.Settings.Default.LastUsername = theUsername;
Properties.Settings.Default.Save();

Then you can access Properties.Settings.Default.LastUsername any time you want to use the last username.

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • You should specify that it should be a user-scoped setting, rather than an application setting. – Merlyn Morgan-Graham Jun 18 '11 at 20:38
  • I used this code, but .LastUsername is unknown function. what should I do? `Properties.Settings.Default.LastUsername = theUsername;` – Iman Jun 18 '11 at 20:45
  • @Iman Hejazi: Go into your project settings, go to the Settings tab, and type "LastUsername" in the first field of the first row and press Enter. Everything should be automatically filled out. – Ry- Jun 18 '11 at 20:48
1
System.IO.File.WriteAllText(path, Environment.UserName);
System.IO.File.ReadAllText(path);

Something like that should work i did not wrote the code.

Rene de la garza
  • 1,259
  • 1
  • 8
  • 7
  • and what are path and Environment.UserName? – Iman Jun 18 '11 at 20:36
  • Environment.UserName is the current logged user to windows, path should be where you want to save the file – Rene de la garza Jun 18 '11 at 20:38
  • -1. This option is no good. `Environment.UserName` is the user that logs into Windows, not a user that would necessarily match the custom authentication system that an application has created. In fact, if the name *did* match, there would be absolutely no reason to store it - just use `Environment.UserName` directly. Also, this option invents yet another way to store application data, when one already exists (see minitech's answer). It also would not be reusable in any way, because you could only store one type of setting per file. – Merlyn Morgan-Graham Jun 18 '11 at 20:40