1

I'm using SQLite with C# and I start by creating a database file with System.IO:

System.IO.File.Create(directoryLineEdit.Text + @"\" + nameLineEdit.Text + ".db");

Now, I try to open this newly created database: (where location is the path to where the file is stored, don't mind the path parameter, that is not relevant here)

public void loadSpaceWalls(string path, string location)
{
    using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + location))
    {
        conn.Open();

        using (SQLiteCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table';";
            cmd.CommandType = System.Data.CommandType.Text;
            SQLiteDataReader rdr = cmd.ExecuteReader();

            Godot.Collections.Array wallsArray = new Godot.Collections.Array();

            while (rdr.Read())
                wallsArray.Add(rdr[0]);

            rdr.Close();
            GetNode(path).Call("updateSpaceWalls", wallsArray);
            wallsArray.Dispose();
        }

        conn.Close();
    }
}

The program crashes with System.Data.SQLite.SQLiteException (0x800007FF): unable to open database file. Now, if I re-open my program and then access the file again (the same code, only difference is that the file has not been 'newly created' by the program, it already exists now), it works fine and doesn't crash.

This does puzzle me 🤔 Any ideas as to why this is?

1 Answer 1

1

File.Create returns a FileStream, which is left open. Unless you're disposing of that stream, nothing else will be able to open the file.

So I suspect all you need to do is change your code to something like:

string dbPath = Path.Combine(directoryLineEdit.Text, $"{nameLineEdit.Text}.db");
using (File.Create(dbPath))
{
    // No-op - we just want to create the file and immediately close the stream.
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.