我正在尝试编写一个程序来将我的 SQL 数据库备份文件复制到 NAS。它以前工作过,但后来我添加了检查路径是否存在,现在当它尝试复制文件时,它得到一个异常说“System.IO.IOException:进程无法访问文件'C:\ Program Files \Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\AdventureWorks2012.bak',因为它正被另一个进程使用。”
我检查了进程资源管理器,没有其他程序正在接触该文件。
我究竟做错了什么?
下面的代码
namespace BackupCopy
{
class Program
{
static void Main(string[] args)
{
// Set Source Path
string sourcePath = @"C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup";
// Verify Source Path Exists
if (!Directory.Exists(sourcePath))
{
Console.WriteLine("Source path does not exist.");
Console.ReadLine();
return;
}
// Backup each file in Array
foreach (string filename in Directory.EnumerateFiles(sourcePath))
{
Backup(filename);
}
}
public static void Backup(string filename)
{
// Pull filename from method input parameter
string fileName = filename;
// Set Paths
string sourcePath = @"C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup";
string targetPath = @"\\prometheus\NAS\DB Backups\mercurys";
// Verify Target Path Exists
if (!Directory.Exists(targetPath))
{
Console.WriteLine("Target path does not exist.");
Console.ReadLine();
return;
}
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a file to another location and
// overwrite the destination file if it already exists.
try
{
System.IO.File.Copy(sourceFile, destFile, true);
}
catch (Exception exc)
{
Console.WriteLine(exc);
Console.ReadLine();
return;
}
}
}
}