Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
hi iuse this piece of code to generate the id for every record.store it in db and show it to the user in my win-form application :
C#
 private static int getID()
 {
	    //read new id from file and return it 
            // 100 is Base id
            int id;
            if (File.Exists("id.txt"))
            {
                TextReader tr = new StreamReader("id.txt");
                id = Int32.Parse(tr.ReadLine());
                id++;
                tr.Close();
                File.WriteAllText(@"id.txt", string.Empty);
                TextWriter tw = new StreamWriter("id.txt");
                tw.WriteLine(id);
                tw.Close();
            }
            else
            {
                id = 100;
                TextWriter tw = new StreamWriter("id.txt");
                tw.WriteLine(id);
                tw.Close();
            }
            return id;
}

is it a good way or not?
what is the best way?
Posted
Updated 28-Nov-12 3:24am
v2

1 solution

Bad, bad way. it has problems in single user, never mind a multiuser environment.

The problem is that files are not meant to be opened by multiple people at the same time, so they have to be locked - and if a file is locked, you can't open it. Plus, if some other task gets in between the read and the write, it could use that number already.

If you want integer IDs, then try using a database, with the ID field set to Identity, and the database system will create the ID for you automatically. Or, if you are not planning on telling your user what their ID is (and they probably don't need to know) why not use a Guid instead?
 
Share this answer
 
Comments
Killzone DeathMan 28-Nov-12 9:46am    
My 5! I like OriginalGriff
Reza Oruji 28-Nov-12 9:49am    
i have to show the id to the user.what is Guid?
Reza Oruji 28-Nov-12 9:55am    
i store it in db as text,if i use int with identity set then how to show the id to the user?
OriginalGriff 28-Nov-12 10:26am    
Never store numbers as text! It makes them a pain to work with. You can always convert them to text when you are presenting them - it's generally a lot easier that way.
A Guid is a Globaly Unique IDentifier: http://en.wikipedia.org/wiki/Globally_unique_identifier
See also: http://msdn.microsoft.com/en-us/library/system.guid.newguid.aspx
Reza Oruji 28-Nov-12 10:46am    
Thank You

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900