Check if destination path contains source path

Darren Rose 281 Reputation points
2021-12-05T16:56:46.253+00:00

Hi

For a backup tool I need to check if the supplied destination path (_destinationpath) contains the supplied source path (_sourcepath)

As for obvious reasons - if copying a folder into a folder which contains that same folder then the source will constantly change thus causing errors / issues with the apps copying process

e.g.

_sourcepath = c:\
_destinationpath = c:\backup

This would be an issue as content of source (c:) would constantly change as it is written to destination (c:\backup) meaning app could crash, have errors or get stuck in a loop

_sourcepath = c:\users\fred\documents
_destinationpath = c:\users\fred\documents\backup

This would be an issue as content of source (c:\users\fred\documents) would constantly change as it is written to destination (c:\users\fred\documents\backup) meaning app could crash, have errors or get stuck in a loop

_sourcepath = c:\folder1
_destinationpath = c:\backup

Would be fine

Done a google on this and can't seem to find a workable solution

Any ideas please?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,937 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,496 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,011 Reputation points
    2021-12-06T12:38:53.997+00:00

    Not fully tested so this may or may not meet your requirements. Play with properties SourceFolder and TargetFolder. The Helper class belongs in it's on file. The code is based off a need to traverse folders lower to upper for a tool I created.

    One button

    using System;  
    using System.Collections.Generic;  
    using System.IO;  
    using System.Windows.Forms;  
      
    namespace DirectoryCode  
    {  
        public partial class Form1 : Form  
        {  
            public Form1()  
            {  
                InitializeComponent();  
            }  
      
            private string SourceFolder => @"D:\OED\Dotnetland";  
            private string TargetFolder => @"C:\OED\Dotnetland";  
      
            private void CompareButton_Click(object sender, EventArgs e)  
            {  
                if (string.Equals(SourceFolder, TargetFolder, StringComparison.OrdinalIgnoreCase))  
                {  
                    MessageBox.Show(@"Pick another path");  
                    return;  
                }  
                Helpers.TraverseFolder += DirectoryExtensionsOnTraverse;  
                Helpers.Traverse(TargetFolder);  
                Helpers.TraverseFolder -= DirectoryExtensionsOnTraverse;  
            }  
      
            private void DirectoryExtensionsOnTraverse(string sender)  
            {  
                if (sender == SourceFolder)  
                {  
                    MessageBox.Show(@"Pick another path");  
                    Helpers.Continue = false;  
      
                }else if (sender == Helpers.DoneMessage && Helpers.Continue)  
                {  
                    MessageBox.Show(@"Good to go");  
                }  
            }  
        }  
      
        public static class Helpers  
        {  
            public delegate void OnTraverse(string sender);  
            public static event OnTraverse TraverseFolder;  
      
            public static bool Continue { get; set; }  
            public static string DoneMessage => "Done";  
      
            /// <summary>  
            /// Traverse folders default to 20 levels deep  
            /// </summary>  
            /// <param name="folderName"></param>  
            /// <param name="level"></param>  
            /// <returns></returns>  
            public static string LoopFolder(this string folderName, int level = 20)  
            {  
                Continue = true;  
      
                var folderList = new List<string>();  
      
                while (!string.IsNullOrWhiteSpace(folderName))  
                {  
                    if (Continue == false)  
                    {  
                        break;  
                    }  
      
                    var parentFolder = Directory.GetParent(folderName);  
      
                    if (parentFolder == null)  
                    {  
                        break;  
                    }  
      
                    folderName = Directory.GetParent(folderName)?.FullName;  
                    folderList.Add(folderName);  
                    TraverseFolder?.Invoke(folderName);  
                      
                }  
      
                if (folderList.Count > 0 && level > 0)  
                {  
                    if (level - 1 <= folderList.Count - 1)  
                    {  
                        return folderList[level - 1];  
                    }  
                    else  
                    {  
                        TraverseFolder?.Invoke(DoneMessage);  
                        return folderName;  
                    }  
                }  
                else  
                {  
                    return folderName;  
                }  
            }  
      
            public static void Traverse(string folder)  
            {  
                folder.LoopFolder();  
            }  
        }  
    }  
    
    
      
    

1 additional answer

Sort by: Most helpful
  1. Jiachen Li-MSFT 24,201 Reputation points Microsoft Vendor
    2021-12-06T05:41:24.403+00:00

    Hi @Darren Rose ,
    You can get the parent directory of the directory by using the Parent Property of the DirectoryInfo Class.
    Then compare the different levels of parent directories of _destinationpath with _sourcepath.
    Best Regards.
    Jiachen Li

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.