0

I've got an absolute path available to me. Say: C:/Program/CoreFiles/Folder1/Folder2/File.txt.

I need to copy that file to C:/Program/Projects/ProjectName/ but it needs to keep Folder1/Folder2/File.txt intact. So the end result should be C:/Program/Projects/ProjectName/Folder1/Folder2/File.txt.

My first attempt at solving this was to try and get the relative path between 2 absolute paths. Found Path.GetRelativePath(string, string) which obviously didn't help as it wasn't meant for WinForms. It would mess up anyway as the final result would be C:/Program/Projects/ProjectName/CoreFiles/Folder1/Folder2/File.txt.

The target directory is empty and I don't know the relative path to copy beforehand other than somehow getting that info out of the absolute path. Since File.Copy won't create folders that don't exist yet, I need to create them first. So how do I get the path that leads up to the file from the CoreFiles directory out of the absolute path?

The only working solution I can come up with is using regex to just replace CoreFiles with Projects/ProjectName in the path string and work with that. But that somehow seems the wrong approach.

icecub
  • 8,615
  • 6
  • 41
  • 70
  • `Directory.CreateDirectory()` does build nested paths. You could use the Uri class and get the `Segments`, skipping Directory names until you find the one you want to start from (`CoreFiles`). Then use `Path.Combine` to rebuild the destination path. – Jimi Apr 06 '20 at 20:13

1 Answers1

1

Since you can't use Path.GetRelativePath. I suggest looking at another answer that describes how to do this yourself. Like here...

Using the method in that answer, you can do the rest of your task as shown below.

string sourcePath = "C:/Program/CoreFiles/Folder1/Folder2/File.txt";
string sourceRoot = "C:/Program/CoreFiles/";
string destinationRoot = "C:/Program/Projects/ProjectName/";

// Use built-in .NET Path.GetRelativePath if you can. Otherwise use a custom function. Like here https://stackoverflow.com/a/340454/1812944
string relativePath = MakeRelativePath(sourceRoot, sourcePath);

// Combine the paths, and make the directory separators all the same. 
string destinationPath = Path.GetFullPath(Path.Combine(destinationRoot, relativePath));

// Create nested folder structure for your files. 
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));

// Copy the file over. 
File.Copy(sourcePath, destinationPath);
BenVlodgi
  • 2,135
  • 1
  • 13
  • 26