将文件复制到新创建的文件夹中,出现错误“正在被另一个进程使用

Copying files into newly created folder giving error "its being used by another process

我尝试创建一个将数据库复制到用户所需位置的子应用程序。虽然弹出一个错误,说我新创建的文件夹正在被另一个应用程序使用(我没有使用任何流阅读器)。

文件正确并且复制到所选目录完全有效,尽管在我创建文件夹并尝试使用他之后问题开始了。

//Snippet
string SourceFile1 = @"C:\Users\user\Documents\DLLTESTBASE.mdf";
string SourceFile2 = @"C:\Users\user\Documents\DLLTESTBASE_log.ldf";
string BackupDirectory = BackupLocation.SelectedPath + "\" + BackupName;
if (!Directory.Exists(BackupDirectory)){
    Directory.CreateDirectory(BackupDirectory);
    }
else{
     MessageBox.Show("A copy has been found :\n" + BackupDirectory , "Copy has been stoped!");
    }

string targetPath1 = BackupDirectory + "\DB.mdf"; 
string targetPath2 = BackupDirectory + "\DB_log.ldf";

try{
     System.IO.File.Copy(SourceFile1, targetPath1);
     System.IO.File.Copy(SourceFile2, targetPath2);
     MessageBox.Show("Copy has been successful.", "Completed!");
    }
catch (Exception ex){
    MessageBox.Show("An error has been occured."+ex,"Operation failed!");}
    }

结果一定是这 2 个文件将在文件夹中。

Sql 数据库文件正在与 Sql 服务一起使用

转到服务

停止"Sql Server"服务

你可以用这个linkstop-or-start-sql-server-service

If u dont want to stop service use this link

你也可以实用地使用附加和分离数据库Attaching-and-Detach

在创建文件之前尝试以下行: File.SetAttribute(targetpath1, FileAttribute.Normal);

如果文件已经存在,您将抛出异常。

您将需要删除文件然后写入它们或使用覆盖参数: System.IO.File.Copy(sourcefile1, targetPath1, true);

抱歉回复晚了,问题似乎是由于我的主应用程序的隐藏隔间引起的,问题在我重新启动计算机后解决,并在我运行主应用程序时再次出现,所以你们是对的 sql 文件连接是 运行(尽管它不可​​见)。

谢谢大家的帮助☺