One of the most annoying boneheaded bugs I run into is trying to create a new file in a directory that does not exist. (At least on Windows/NTFS, not sure about other OS/FS combinations.)
Here's how it usually happens in C#:
const string directoryName = @"logDir\";
// This would prevent the exceptions.
//Directory.CreateDirectory(directoryName);
const string logMessage = "Logging a line!";
try
{
const string fileName = directoryName + "Log.txt";
File.AppendAllText(fileName, logMessage + Environment.NewLine);
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("Yup, complaining about directory not found when trying to append.");
}
try
{
const string databaseName = directoryName + "Log.sqlite";
using (var connection = new SQLiteConnection($"Data Source={databaseName};Version=3;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "CREATE TABLE IF NOT EXISTS log(message); INSERT INTO log(message) VALUES(@message);";
command.Parameters.AddWithValue("@message", logMessage);
command.ExecuteNonQuery();
}
connection.Close();
}
}
catch (SQLiteException)
{
Console.WriteLine("Yup, even sqlite, which will create the file if it doesn't exist, requires a separate step to create a directory.");
}
If the API provides the ability to append files or create them if it doesn't exist, why wouldn't that same ability also create the required directory if it doesn't exist? What is the rationale behind such a behaviour?
May be a dumb question, but I had to ask because I'm annoyed when an easy to miss extra step is required for code to work properly, and I don't see the benefits.