· 8 years ago · Dec 14, 2017, 10:46 AM
1const string directoryName = @"logDir";
2
3// This would prevent the exceptions.
4//Directory.CreateDirectory(directoryName);
5
6const string logMessage = "Logging a line!";
7try
8{
9 const string fileName = directoryName + "Log.txt";
10 File.AppendAllText(fileName, logMessage + Environment.NewLine);
11}
12catch (DirectoryNotFoundException)
13{
14 Console.WriteLine("Yup, complaining about directory not found when trying to append.");
15}
16
17try
18{
19 const string databaseName = directoryName + "Log.sqlite";
20 using (var connection = new SQLiteConnection($"Data Source={databaseName};Version=3;"))
21 {
22 connection.Open();
23 using (var command = connection.CreateCommand())
24 {
25 command.CommandText = "CREATE TABLE IF NOT EXISTS log(message); INSERT INTO log(message) VALUES(@message);";
26 command.Parameters.AddWithValue("@message", logMessage);
27 command.ExecuteNonQuery();
28 }
29 connection.Close();
30 }
31}
32catch (SQLiteException)
33{
34 Console.WriteLine("Yup, even sqlite, which will create the file if it doesn't exist, requires a separate step to create a directory.");
35}