Skip to main content
Post Closed as "Not suitable for this site" by dfhwze, t3chb0t, Toby Speight, pacmaninbw, AJNeufeld
tag
Link
dfhwze
  • 14.2k
  • 3
  • 40
  • 101
Source Link
TomSelleck
  • 373
  • 1
  • 9

Finding the next available filename

We're having a small debate in work about the following piece of code:

private string GetNextFileName(string fileName)
{
    int index = 1;
    
    string nextName = $"{fileName}_{index}.png";
    
    while (File.Exists(nextName))
    {
        nextName = $"{fileName}_{++index}.png";
    }

    return nextName;
}

Is there anything particularly dangerous about this piece of code? It sort of feels dodgy having the condition in a while loop.

Would it be better to use a for-loop with a breakout if the number gets too high?

e.g.

private string GetNextFileName(string fileName)
{
    int i = 1;
    string nextName = $"{fileName}_{i}.png";
    
    for (; i < 100; ++i)
    {
        if (!File.Exists(nextName))
        {
            return nextName;
        }
        nextName = $"{fileName}_{i}.png";
    }

    throw new ApplicationException("Unable to get free filename");
}