I am writing a large number of files (80,000 to be exact) that are on my hard drive and copying them to my flash drive. Things start ok, but at the 29,648th file, I get an IOException stating The directory or file cannot be created.
I used to different ways of directory copying that I've found via the interwebs:
https://msdn.microsoft.com/en-us/library/bb762914(v=vs.110).aspx
Copy the entire contents of a directory in C#
And they both ended with the same result.
Any ideas on why it fails exactly there? The flash drive has enough space, and I know the file is not duplicate, since I am starting with a blank flash drive.
class Program
{
static void Main(string[] args)
{
DirectoryCopy(Directory.GetCurrentDirectory(), "F://", true);
}
static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
}