在Windows 7上的Directory.Move期间发生IOException

时间:2011-04-06 15:41:38

标签: c# ioexception

我继承了最近部署到Windows 7工作站的C#应用​​程序。在此之前,它已经在许多Windows XP工作站上运行,而没有遇到下面的问题。

有问题的代码部分尝试使用线程中的循环来移动目录。在Windows 7计算机上捕获 IOException 。根据MSDN(http://msdn.microsoft.com/en-us/library/system.io.directory.move.aspx IOException 可能由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 个答案:

答案 0 :(得分:4)

我首先将异常消息输出到消息框中,看看它是否通过执行此操作明确了解异常的原因:

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

的情况下对我的看法
相关问题