Several points of confusion here:
1)
Path.GetFullPath(xmlFile.Name)
will combine the name of the XML file with
the current working directory. That will
not be the same as the full path of the XML file, which you can retrieve using
xmlFile.FullName
;
2) You don't actually want the full path of the XML file; since you're trying to copy other files to the path, you want the path of the parent directory. You can retrieve that using
xmlFile.DirectoryName
;
3) Since
tifLoc
is a directory, you can't use
File.Copy
to copy it elsewhere. Unfortunately, you need to copy the individual files separately.
4)
Directory.GetDirectories(...).FirstOrDefault()
will return
null
if the directory doesn't exist. In that case, you'll get a
NullReferenceException
on the next line, when you try to call
.ToString()
on the returned
string
value.
Also, you'll probably want to use
EnumerateFiles
and
EnumerateDirectories
instead of their
Get*
counterparts, particularly if there are a lot of files to process. The
Get*
versions have to load all matches into memory before you can start processing them, whereas the
Enumerate*
versions let you start processing as soon as the first match is found.
Something like this should work:
DirectoryInfo diCopyFrom = new DirectoryInfo(textBox1.Text);
DirectoryInfo diCopyTo = new DirectoryInfo(textBox2.Text);
foreach (FileInfo xmlFile in diCopyTo.EnumerateFiles("*.xml", SearchOption.AllDirectories))
{
string tifDirectoryName = Path.GetFileNameWithoutExtension(xmlFile.Name);
DirectoryInfo sourceDirectory = diCopyFrom.EnumerateDirectories(tifDirectoryName, SearchOption.AllDirectories).FirstOrDefault();
if (sourceDirectory != null)
{
string destinationDirectoryName = xmlFile.DirectoryName;
foreach (FileInfo tifFile in sourceDirectory.EnumerateFiles("*.tif"))
{
string destFileName = Path.Combine(destinationDirectoryName, tifFile.Name);
tifFile.CopyTo(destFileName, true);
}
}
}