System.IO.DirectoryNotFoundException after deleting an empty folder and recreating it

后端 未结 7 2217
我在风中等你
我在风中等你 2021-02-13 04:37

I want to copy a folder, and i want to delete destination folder first. So I am deleting destination folder then recreate it and then copy files. The problem is that i get the <

7条回答
  •  礼貌的吻别
    2021-02-13 05:10

    Ok This is very strange. the exception only happen when the destination folder is empty. but adding the folowing line after the destination folder deletion seem to solve the problem. the line : MessageBox.Show("folder " + destFolder + "folder was deleted", "alert");

    static public void CopyFolder(string sourceFolder, string destFolder)
        {
            if (Directory.Exists(destFolder)) // check if folder exist
            {
                Directory.Delete(destFolder, true);  // delete folder
                MessageBox.Show("folder " + destFolder + "folder was deleted", "alert");
            }
            Directory.CreateDirectory(destFolder); // create folder
    
            string[] files = Directory.GetFiles(sourceFolder);
            foreach (string file in files)
            {
                string name = Path.GetFileName(file);
                string dest = Path.Combine(destFolder, name);
                File.Copy(file, dest, true);
                FileInfo fileinfo = new FileInfo(dest); // get file attrib
                if (fileinfo.Attributes != FileAttributes.ReadOnly) // check if read only 
                    File.SetAttributes(dest, FileAttributes.Normal);
            }
    

    so putting a MessageBox.show after the deletion causes the System.IO.DirectoryNotFoundException to go away. its as if the fact that there is a small delay after the deletion , the recreation of the folder goes well. i guess i will find a work around this, but if someone knows what is causing this and the way to solve it , i will be very happy to hear it.

提交回复
热议问题