-2

I've got a list of Base64 strings that I'm writing to jpeg files on disk by looping through the list. The problem is that not all the files get written. It seems like the operating system doesn't have enough time to write a file to disk before my code moves on to the next item in the list. When I set break point to slow the code, all files get written. I'm using File.WriteAllBytes in C#:

private string WriteJpegs(string photoDate, List<string> photos)
{
...
for (int i=0; i < photos.Count; i++)//loop through list and write jpeg file for each base64 
string
        {
            Random rnd = new Random();
            int num = rnd.Next(1, 20000000);
            string fileName = photoDate + "_" + Convert.ToString(num) + ".jpg";
            string filePath = "PhotoFolder\";
            byte[] imageBytes = Convert.FromBase64String(photos[i].ImageData64);
            File.WriteAllBytes(filePath + fileName, imageBytes);//if I break here all files get written
        }

Do I need to do some kind of asynch operation?

Thanks

Pete

... }

pvitt
  • 1,005
  • 4
  • 14
  • 31
  • 3
    *"The problem is that not all the files get written. It seems like the operating system doesn't have enough time to write a file to disk before my code moves on to the next item"* - that should not be possible though. the thing is, you might accidentally replace existing file(s) using that `File.WriteAllBytes`. especially with reinitializing `Random` in a loop multiple times. – Bagus Tesa Jun 30 '22 at 23:26
  • 4
    Standard bug with Random, creating it over and over again in a short amount of time will generate the same random numbers. Move it out of the loop. But it is still a bug, no guarantee that the code won't generate the same filename twice. It isn't obvious what was intended, consider using a simple counter. Or use System.Guid to generate unique names. – Hans Passant Jun 30 '22 at 23:30
  • Thanks so much -- random was the problem. Switched to counter and it works great! – pvitt Jun 30 '22 at 23:40
  • Side note: please re-read [mre] (as code you posted in the question is not valid C# which even weak SO highlighter caught) and https://meta.stackoverflow.com/questions/260776/should-i-remove-fluff-when-editing-questions (as half of your post seem to be of thank you notes). – Alexei Levenkov Jul 01 '22 at 00:06

1 Answers1

0

the question was answered by Bagus and Hans in comments -- use a counter instead of Random

pvitt
  • 1,005
  • 4
  • 14
  • 31