Click here to Skip to main content
13,043,865 members (48,129 online)
Rate this:
Please Sign up or sign in to vote.
See more:
iuse this piece of code to generate the id for every it in db and show it to the user in my win-form application :
 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());
                File.WriteAllText(@"id.txt", string.Empty);
                TextWriter tw = new StreamWriter("id.txt");
                id = 100;
                TextWriter tw = new StreamWriter("id.txt");
            return id;

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

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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?
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:
See also:
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170713.1 | Last Updated 28 Nov 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100