Search code examples
c#sqlitesqlconnection

Connecting to SQLite DB over network


I am currently mapping a network drive and connecting to the file (Z:\Data\Database.db) that way. I would like to be able to just use a relative path (\server\Data\Database.db) in the connection string but it is giving me a SQLite error "unable to open database file". A Directory.Exists(\\server\Data\Database.db); check is returning true.

Here is the attempt to open the connection using the path "\\server" as the argument:

public static OpenDB(string dbPath)
{
    using (SQLiteConnection conn = new SQLiteConnection($"Data Source={Path.Combine(dbPath, "Data\\Database.db")}"))
    {
        if (dbPath != null && dbPath != "")
        {
            try
            {
                conn.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Unable to Open Database", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

Solution

  • This was the solution that I used. It is a combination of advice from jdweng and Shawn. First I made the path dbPath be an administrative share drive. From there I made the program make a temporary local copy of the database from the administrative share:

    private static void MakeTempDatabaseCopy(string dbPath, string exePath)
    {
        try
        {
            File.Copy(Path.Combine(dbPath, "Data", "Database.db"), Path.Combine(exePath, "Temp", "Database.db"), true);
            FileInfo directoryInfo = new FileInfo(Path.Combine(exePath, "Temp", "Database.db"));
            directoryInfo.Attributes = FileAttributes.Temporary;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error Retrieving Database", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
    

    After that all methods can read from the local copy. Since the File.Copy() uses the Boolean, anything that requires a refresh of the database can just overwrite the local copy with a fresh copy from the administrative share. Hope this helps!