[英]IOException access denied when Directory.Move subfolder and parent folder
[英]IOException during Directory.Move on Windows 7
我繼承了一個C#應用程序,該應用程序最近已部署到Windows 7工作站。 在此之前,它已經在許多Windows XP工作站上運行,而沒有遇到以下問題。
有問題的代碼部分嘗試使用線程中的循環移動目錄。 在Windows 7計算機上,捕獲到IOException 。 根據MSDN( http://msdn.microsoft.com/zh-cn/library/system.io.directory.move.aspx ), IOException可能由三種情況引起。 我想知道循環是否要嘗試多次移動目錄,這可能會導致“ 目標已經存在 ”的情況。
症狀是警告MessageBox反復顯示,但移動最終將成功。 從我對代碼的解釋來看,這應該僅在60秒(300 * 200ms)之后發生,但似乎幾乎立即發生。
由於我在C#方面的經驗很少,而在線程方面的經驗甚至更小,因此我很茫然! 我想知道所討論的代碼是否明顯有問題。
代碼的相關部分如下。
public static string archiveBatch(Batch myBatch, string from)
{
string to = "";
to = FileSystemManager.getArchivePath(myBatch, System.IO.Path.GetFileName(from));
threadedMove tm = new threadedMove(from ,to);
Thread t = new Thread(new ThreadStart(tm.run));
t.Priority = ThreadPriority.Highest;
t.Start();
return to;
}
private class threadedMove
{
string archivePath;
string fromPath;
public threadedMove(string from, string to)
{
archivePath = to;
fromPath = from;
}
public void run()
{
int errorCounter = 0;
while (true)
{
errorCounter++;
if (TryToMove(fromPath, archivePath)) { break; }
Thread.Sleep(200);
if (errorCounter > 300)
{
throw (new Exception("Warning: could not archive file from "+fromPath+" to "+archivePath));
}
}
}
}
private static bool TryToMove(string source, string destination)
{
try
{
//check if path is file or folder
if (System.IO.File.Exists(source))
{
//it is a file
if (!System.IO.File.Exists(destination))
{
System.IO.File.Move(source, destination);
}
}
else
{
//it is a directory
if (!System.IO.Directory.Exists(destination))
{
System.IO.Directory.Move(source, destination);
}
}
return true;
}
catch (IOException)
{
MessageBox.Show("Warning: could not archive file from " + source + " to " + destination", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
}
首先,將異常消息輸出到消息框中,以查看其是否確切說明了為什么通過以下方式引發異常:
catch (IOException ex)
{
MessageBox.Show("Warning: could not archive file from " + source + " to " + destination + ". Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
一旦知道原因,便可以查看如何預防
還有什么是Batch
? 看起來它可能正在嘗試將其移至同一位置,這就是我對它的外觀,而又不了解Batch
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.