我遇到了一个奇怪的问题(这可能是我缺乏知识),我提出了令人讨厌的代码:
try
{
f.Delete();
fTemp.MoveTo(f.FullName);
Console.WriteLine("INFO: Old file deleted new file moved in > {0}", f.FullName);
}
catch (IOException ex)
{
Console.WriteLine("ERROR: Output file has IO exception > {0}", f.FullName);
Environment.ExitCode = 1;
}
Run Code Online (Sandbox Code Playgroud)
f和fTemp是FileInfo对象.因此,如果我使用代码执行此操作,其中f是在媒体播放器中播放的视频文件,则会抛出异常.这工作正常,如预期的那样.现在,当我关闭媒体播放器时,它会删除文件!?即使我的申请被长期关闭.即使我关闭Visual Studio,当我关闭媒体播放器时,它仍会删除该文件.好像某个回调正在某处设置,以确保文件在某个时刻被删除.这种不受欢迎的行为.但我无法弄清楚究竟出了什么问题......
结果现在:
if (!IsFileLocked(f))
{
try
{
f.Delete();
fTemp.MoveTo(f.FullName);
Console.WriteLine("INFO: Old file deleted new file moved in > {0}", f.FullName);
}
catch (IOException ex)
{
Console.WriteLine("ERROR: Output file has IO exception > {0}", f.FullName);
Environment.ExitCode = 1;
}
catch (UnauthorizedAccessException ex)
{
Environment.ExitCode = 2; …Run Code Online (Sandbox Code Playgroud) 我在多次重命名目录时遇到问题,似乎锁定了该文件.
// e comes from a objectListView item
DirectoryInfo di = (DirectoryInfo)e.RowObject;
DirectoryInfo parent = Directory.GetParent(di.FullName);
String newPath = Path.Combine(parent.FullName, e.NewValue.ToString());
// rename to some temp name, to help change lower and uppercast names
di.MoveTo(newPath + "__renameTemp__");
di.MoveTo(newPath);
// Trying to cleanup to prevent directory locking, doesn't work...
di = null;
parent = null;
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
Run Code Online (Sandbox Code Playgroud)
任何帮助都非常感谢,因为第一次重命名工作正常,但是当尝试在重命名的文件夹上执行新的重命名时,它会引发异常:
该进程无法访问该文件,因为该文件正由另一个进程使用.mscorlib.dll中发生了'System.IO.IOException'类型的第一次机会异常
所以第一次重命名该文件夹工作,第二次抛出异常,我猜测应用程序持有新文件夹的锁,但如何解决它?我应该能够两次重命名文件夹吗?