我有这个问题:我处理文件后需要移动到另一个文件夹: 实际上我这样做:
FileInfo file = new FileInfo(BW_FullPathPhoto);
file.MoveTo(sFolderCopy + "\\" + System.IO.Path.GetFileName(BW_FullPathPhoto));
但有时会给我一个错误,即该文件当前正在使用且无法移动......
我知道如果我重命名正在使用的文件,那么Windows让我这样做......可以重命名文件而不移动(我认为移动执行副本并且删除后)
答案 0 :(得分:0)
public static class Pathy
{
internal enum MoveFileFlags
{
MOVEFILE_REPLACE_EXISTING = 0x1
, MOVEFILE_COPY_ALLOWED = 0x02
, MOVEFILE_DELAY_UNTIL_REBOOT = 0x04
, MOVEFILE_CREATE_HARDLINK = 0x10
, MOVEFILE_WRITE_THROUGH = 0x8
, MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x20
}
[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "MoveFileEx")]
internal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, MoveFileFlags dwFlags);
public bool MoveOrReboot(FileInfo fi, DirectoryInfo di)
{
fi?.Refresh();
if (!(di?.Exists ?? false)) throw new DirectoryNotFoundException(di.FullName);
if (fi?.Exists ?? false)
{
try
{
fi.MoveTo(di.FullName + System.IO.Path.DirectorySeparatorChar + fi.Name);
return true;
}
catch (IOException e)
{
switch (e.HResult)
{
case -2147024864: //equivalent 'file in use' error
if (MoveFileEx(fi.FullName, di.FullName + System.IO.Path.DirectorySeparatorChar + fi.Name, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT))
{
return false;
}
break;
default:
throw e;
}
}
catch (Exception e)
{
throw e;
}
}
else throw new FileNotFoundException(fi.FullName);
}
}
编辑:将该函数放入一个类中,并添加一个返回值以确定操作系统是否需要重新启动。
用法:
try
{
if (!Pathy.MoveOrReboot(fi,di)) reboot_needed = true;
}
catch (Exception e)
{
//...
}