I find that I am often writing files where the names either:
- Need to be incremented (rather than overwriting a file that already exists in the directory with the same name)
- Need to be timestamped
And, so, I've created the following methods to do so:
public static string CreateDatedFileName(string directory, string filename, string DateTimeFormat = "yyyy-MM-dd", bool AppendNumberIfNameAlreadyExists = true)
{
if (!CheckIfDirectoryExists(directory))
throw new ArgumentException(string.Format("The specified directory - {0} - does not exist", directory));
string formatedTemplate = "{0} - {1}.{2}";
var fileNameWithoutExtension = filename.Split('.')[0];
var fileExtension = filename.Split('.')[1];
var DateValue = DateTime.Now.ToString(DateTimeFormat);
string newname = String.Format(formatedTemplate, fileNameWithoutExtension, DateValue, fileExtension);
string path = Path.Combine(directory, newname);
if (!AppendNumberIfNameAlreadyExists)
return Path.Combine(directory, newname);
else
return CreateFileName(directory, newname, true);
}
public static string CreateFileName(string directory, string filename, bool AppendNumberIfNameAlreadyExists = true)
{
if (!CheckIfDirectoryExists(directory))
throw new ArgumentException(string.Format("The specified directory - {0} - does not exist", directory));
string formatedTemplate = "{0}{1}.{2}";
var fileNameWithoutExtension = filename.Split('.')[0];
var fileExtension = filename.Split('.')[1];
string newname = String.Format(formatedTemplate, fileNameWithoutExtension, string.Empty, fileExtension);
string path = Path.Combine(directory, newname);
int AppendDigit = 0;
while (AppendNumberIfNameAlreadyExists && CheckIfFilePathExists(path))
{
++AppendDigit;
newname = String.Format(formatedTemplate, fileNameWithoutExtension, "_" + AppendDigit, fileExtension);
path = Path.Combine(directory, newname);
}
return path;
}
public static bool CheckIfDirectoryExists(string directory)
{
return System.IO.Directory.Exists(directory);
}
public static bool CheckIfFilePathExists(string path)
{
return System.IO.File.Exists(path);
}
I'm just curious to know if this is an efficient way to accomplish this and, if not, I'd really like to learn why so as to become a better coder overall.
AppendNumberIfNameAlreadyExists
? – Mat's Mug♦ 22 hours agocamelCase
;-) – Mat's Mug♦ 22 hours agoCheckIfDirectoryExists()
. It doesn't make a lot of sense to me when used as!CheckIfDirectoryExists()
- what's a "not check..."? If a method returns a bool I would prefer a name that makes "English" sense when used in an if statement. E.g.if (DirectoryExists("xxx"))
orif (!DirectoryExists("xxx"))
– eurotrash 21 hours ago