Search code examples
c#file-managementnetwork-drive

C# File.copy and Directory.CreateDirectory working on Win10 but in Win7 it appends folder to parent folder


The same code, one on windows 10, the other on windows 7. The idea is to have a directory from a network drive replicate over to a local drive. On windows 10, the machine I am writing it on, it works perfectly fine as intended. On windows 7, the target machine, it 'works' but the sub folder structure is messed up.

Example,

C:\target -> the target location

C:\targetNewFolderName1 -> What its being copied to

C:\targetNewFolderName2

C:\targetNewFolderNameN

When it should be doing this below,(which it is, on windows 10, not on windows 7)

C:\target -> the target location

C:\target\NewFolderName1 -> What its being copied to

C:\target\NewFolderName2

C:\target\NewFolderNameN

Master is a network directory, @"\\server\fu\bar\target"

Slave is a local directory, @"C:\target"

These are passed to the function.

Function header, private void CheckMasterToSlave(string MasterPath, string SlavePath, string BackupPath, string[] MasterFilesList, string[] SlaveFilesList)

The below code snipit is within a foreach; foreach (string master in MasterFilesList).

    log.Info(master + " doesnt exist, copying");
    string directoryCheck = (SlavePath + master.Substring(MasterPath.Length)).Substring(0, 
                            (SlavePath + master.Substring(MasterPath.Length)).LastIndexOf("\\"));
    if (!Directory.Exists(directoryCheck))
    {
       log.Debug(directoryCheck + " Directory not present, touching.");
       try
       {
           Directory.CreateDirectory((SlavePath + 
                                    master.Substring(MasterPath.Length)).Substring(0, (SlavePath + 
                                    master.Substring(MasterPath.Length)).LastIndexOf("\\")));
       }
       catch
       {
           log.Error(master + " directory failed to be created in slave environment.");
       }
   }
   try
   {
       File.Copy(master, SlavePath + master.Substring(MasterPath.Length));
       log.Info(SlavePath + master.Substring(MasterPath.Length) + " Successfully created.");
       BackupFile(master.Replace(MasterPath, SlavePath), BackupPath, SlavePath);
   }
   catch
   {
       log.Error(master + " failed to copy, backup has been halted for this file.");
   }

I do not understand why this works as intended on windows 10 but moving it to windows 7 causes this issue. What would be causing this and how can I stop the new folder from appending to the parent folder in windows 7?


Solution

  • Use Path.Combine to build a path name from different path components instead of just using string concatenation.