2011-04-06 58 views
0

我已经继承了最近部署到Windows 7工作站的C#应用​​程序。在此之前,它已在许多Windows XP工作站上运行,而未出现下面的问题。Windows 7上的Directory.Move时发生IOException

有问题的代码段尝试使用线程中的循环移动目录。在Windows 7机器上发现一个IOException。根据MSDN(http://msdn.microsoft.com/en-us/library/system.io.directory.move.aspxIOException可能由3个条件引起。我想知道如果循环可能试图移动目录不止一次,这可能会导致“目标已存在”条件。

症状是重复显示警告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; 
     } 
    } 
+1

我宁可不将线程优先级设置为最高。 – jfs 2011-04-06 15:45:03

+0

是的,我看到那个,并且想,“嗯......”。我想知道是否已经完成尝试并确保线程在300次迭代之前完成其工作。 – hmallett 2011-04-06 15:46:58

+0

无论如何,改变.Net中的线程优先级以获得任何可观察的效果是非常罕见的,所以我也会删除该线。 – MusiGenesis 2011-04-06 15:47:40

回答

4

我会通过输出异常消息到这些URL,看它是否揭示了正是为什么异常正被这样投入了一些光开始:

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

+0

谢谢!目标位置总是不同(根据MessageBox中的错误),所以我认为我们对于源和目标是相同的问题。 – hmallett 2011-04-06 16:12:22

+0

+1,故意隐藏您需要诊断问题的* exact *消息始终是一个错误。没有人可以诊断'它没有工作'的信息。 – 2011-04-06 16:44:25

相关问题