public static string getFreeFile(string path)
{
string filename = Path.GetRandomFileName();
string random = path + filename;
//check for existence or just return the random file?
if (File.Exists(random))
{
return getFreeFile(path);
}
else
{
return filename;
}
}
if you receive a random file name there is a very slight chance it might exist already, so if you overwrite this file, chances are, that you destroy a file you didn’t want to destory. To prevent this you can check for existence before you use the randomly generated filename. However the probability of getting the same name twice is almost zero. So the question is, if an existence check is worth it?
good approach when there are only a few files in the folder, but let’s assume you have 100 files in the folder you have to loop through all 100 files. I finally used this method:
public static string getFreeFolderName(string path, int length=2)
{
for (int i = 0; i < Mathf.Pow(5, length); i++)
{
string name = StringTools.getRandomString(length) + "/";
string random = path + name;
if (!Directory.Exists(random))
{
return random;
}
}
return getFreeFolderName(path, length + 1);
}
public class StringTools
{
public static string getRandomString(int length)
{
var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[length];
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[UnityEngine.Random.Range(0, chars.Length - 1)];
}
var finalString = new String(stringChars);
return new string(stringChars);
}
}
still not perfect but it reduces the amount of Exists calls, and keeps the folder name small, because some systems got limited path sizes.
Well, the work on your code and after cleaning up your string-garbage and whatnot probably will be more than one or two File.Exists calls. And it is really unnecessarily complicated.
I mean you still call “Directory.Exists(random)” and on the top of that you do a lot of stuff you didn’t before and generate garbage. That’s why I don’t understand why is it better operation?
it’s just to keep the filename smaller than when using the default Path.GetRandomFileName(), probably a waste of coding time, just wanted to make sure, that the path name doesn’t exceed any limits
I think you’re wasting your time trying to solve a problem that doesn’t exist yet. You’ve made your code more complicated, and Exists get called more in your new code.