我正在尝试编写一个程序来将我的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;
}
}
}
}
答案 0 :(得分:0)
问题是程序在枚举目录中的文件时锁定了文件句柄。
取代它;
// Backup each file in Array
foreach (string filename in Directory.EnumerateFiles(sourcePath))
{
Backup(filename);
}
有了这个;
Backup("AdventureWorks2012.bak");
解决问题。