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");
}