Copy File to another Folder Structure

170 views Asked by At

I am currently trying to create a program, that should copy a folder structure into a directory.

Here is an example:
C:\test1\folder\folder\file.txt should end up in C:\test2\folder\folder\file.txt

I have a List<FileSystemInfo for the Source-Folder and now I need to copy the files and create the Folders like in the example.

I would like to do this without pathname-strings because of the Filename-Limitation of 260 Characters.

I have this code to copy the files with pathnames:

string destFile = BackupOptions.DestinationFolder + sourceFileInfo.FullName;
string destParent = Directory.GetParent(destFile).FullName;
string backupFolder = destParent + @ "\backupFolder";
try {
 while (!Directory.Exists(destParent)) {
  if (!Directory.Exists(destParent)) {
   Directory.CreateDirectory(destParent);
  }
 }
 FileAttributes fileAttributes = sourceFileInfo.Attributes;
 if ((fileAttributes & FileAttributes.Directory) == FileAttributes.Directory) {
  Directory.CreateDirectory(destFile);
 } else {
  FileInfo file = (FileInfo) sourceFileInfo;
  file.CopyTo(destFile, true);
 }
} catch (Exception e) {
 Console.Write(e.Message);
 return false;
}

Does someone knows how to copy a file/directory just with the FileSystemInfo-Object of that File/Object?

1

There are 1 answers

0
usr On

I don't think any of the .NET IO classes support long paths right now. No way around that that I know of. In the .NET 4.0 time frame the team made a public attempt to add that but it never landed.

Use a search engine to find a library that adds this. The library internally uses PInvoke (which of course you could use directly at less convenience). I think AlphaFS is a known name.

You can simplify your code: Directory.CreateDirectory creates multiple levels at the same time and does not fail when the directory already exists. This is almost always what you need.

then use it with the parent-folder string of the object and create the directory in the destination folder

Not 100% sure what you mean but it could well be right :)