C#“正由另一进程使用,因此该进程无法访问该文件”在复制删除SQLite数据库文件时出现

今天在做系统中数据库文件导入的时候,出现了“正由另一进程使用,因此该进程无法访问该文件”的错误。

我的操作是把目标文件复制到当前文件夹下,然后将记录系统设置的数据先从旧的文件中放到新的文件中,使用了SQLiteCommand的ExecuteNonQuery()方法进行更新。

                    System.IO.File.Copy(localFilePath, Path1, true);


                    SQLiteConnection connection = new SQLiteConnection("Data Source =Path1;");
                    connection.Open();
                    if (connection.State == System.Data.ConnectionState.Closed)
                        throw new Exception("数据库打开失败!");

                    DataTable dataTableOri = new DataTable();
                    DataOpera db = new DataOpera();//这是我自己的数据操作类,连接到Path2的旧数据库文件
                    db.fillDataTable(ref dataTableOri, "SELECT mset FROM sys WHERE annotation = 'password'", "sys");

                    string comN = "UPDATE sys SET mset = '" + dataTableOri.Rows[0][0].ToString() + "' WHERE annotation = 'password'";
                    SQLiteCommand com = new SQLiteCommand(comN, connection);
                    if (com.ExecuteNonQuery() <= 0)
                        throw new Exception("密码插入失败!");

                    System.IO.File.Copy(Path1, Path2, true);
                    File.Delete(Path1);

但是一直报错

在Path1的Delete时候出错。查阅资料以为是线程的问题。

后来调试发现是操作连接了数据库的对象没有释放。将SQLiteCommand、SQLiteConnection都释放掉就可以了


                    System.IO.File.Copy(localFilePath, Path1, true);


                    SQLiteConnection connection = new SQLiteConnection("Data Source =Path1;");
                    connection.Open();
                    if (connection.State == System.Data.ConnectionState.Closed)
                        throw new Exception("数据库打开失败!");

                    DataTable dataTableOri = new DataTable();
                    DataOpera db = new DataOpera();//这是我自己的数据操作类,连接到Path2的旧数据库文件
                    db.fillDataTable(ref dataTableOri, "SELECT mset FROM sys WHERE annotation = 'password'", "sys");

                    string comN = "UPDATE sys SET mset = '" + dataTableOri.Rows[0][0].ToString() + "' WHERE annotation = 'password'";
                    SQLiteCommand com = new SQLiteCommand(comN, connection);
                    if (com.ExecuteNonQuery() <= 0)
                        throw new Exception("密码插入失败!");

                    com.Dispose();
                    db.Dispose();
                    connection.Dispose();

                    System.IO.File.Copy(Path1, Path2, true);
                    File.Delete(Path1);

猜你喜欢

转载自blog.csdn.net/Colin_Downey/article/details/83547471
今日推荐