By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,711 Members | 2,144 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,711 IT Pros & Developers. It's quick & easy.

Problem with writing multiple text files

P: 2
Hi,

I'm writing a windows application in C# using VS 2003.
I got stuck where it has to write multiple output text files. Here's my piece of code:

Expand|Select|Wrap|Line Numbers
  1. for loop
  2. {
  3.     Random r = new Random();
  4.     //use millisecond and random to avoid similar filename
  5.     string a_filename = "alert_" + r.Next(1000) + DateTime.Now.Millisecond.ToString() + ".txt";
  6.  
  7.     using (StreamWriter sw = new StreamWriter(a_filename))
  8.     {
  9.         using (TextWriter ssw = TextWriter.Synchronized(sw))
  10.         {
  11.             ssw.Write("some text");
  12.         }
  13.     }
  14. }
  15.  
What happen is let's say it's supposed to write 7 output txt files, but then I found out it's only writing 4.
If I try to using debug mode and step into the code line by line using F11, then it can successfully write 7 output files!
But if I run the application again (not using debug), then it only writes 4 output files.

Does anybody have a suggestion to this problem?

Thanks & Regards,

Adrian
Apr 1 '09 #1
Share this Question
Share on Google+
2 Replies


tlhintoq
Expert 2.5K+
P: 3,525
Stop testing with random number and eliminate the possiblity of duplicates.
Make new file names down to 3 points of the second.

String filename = DateTime.Now.ToString("HHmmss.fff");

and check if the file already exists before you try to write to it. If it does choose a new name.
Apr 1 '09 #2

P: 2
Argh.. stupid me didn't think of that... I thought it's a slim chance for a random generator to repeat same number. The file is overwriting each other.
Thanks tlhintoq!
Apr 1 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.