Home > Mobile >  SQlite loads database from the wrong folder in c# on windows startup
SQlite loads database from the wrong folder in c# on windows startup

Time:01-21

I get this error when app starts on windows startup but the app runs perfect when i open it while the windows is running .

SQLite error (14): cannot open file at line 47640 of [b0c4230c89]
Exception thrown: 'System.Data.SQLite.SQLiteException' in System.Data.SQLite.dll
SQLite error (14): os_win.c:47639: (2) winOpen(C:\WINDOWS\System32\qubanga.db) - The system cannot find the file specified

This is the sqlite database connection the program uses to retrive the database .

 try
            {
               SQLiteConnection sqlite_conn = new SQLiteConnection("Data Source=database.db; Version = 3; New = True; Compress = True; ");
                sqlite_conn.Open();



                SQLiteCommand sqlite_cmd;
                
                string createTable = "Insert into "   table   "("   columns   ") Values(" values ");";

                sqlite_cmd = sqlite_conn.CreateCommand();
                sqlite_cmd.CommandText = createTable;
                var query = sqlite_cmd.ExecuteNonQuery();
              
                if (query == 1)
                    result = true;

            }

Set StartUp for the program

 public  static void  SetStartup()
        {
            RegistryKey rk = Registry.CurrentUser.OpenSubKey
                ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

           
                rk.SetValue("AppName", Application.ExecutablePath);
           

        }

CodePudding user response:

If your application is in a different folder than the System32 folder (which I hope it is) your code will set the registry key to that folder path. Run regedit and navigate to that key to check. So on startup Windows will look to the Application folder for the db and not to the System32 folder. Try this to set it to the System32 folder instead.

rk.SetValue("AppName", Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "qubanga.db" );

CodePudding user response:

So After working on the problem with the solution provided above ,I realize that the program on Windows start up was being executed from C:\WINDOWS\System32\ instead of the location where it's installed . I solved the issues by changing the Working Directory of the application .I got this Idea from @Caius

public static void SetWorkingDirectory()
        {
            string excePath = AppDomain.CurrentDomain.BaseDirectory;

            Directory.SetCurrentDirectory(excePath);
                //Console.WriteLine(Directory.GetCurrentDirectory());



        }
  •  Tags:  
  • Related