none
Replace & combine of folder name RRS feed

  • Question

  • I want replace existing file path with new folder.

    For example,

    ROOTPATH = @"D:\Original";

    filepath = @"D:\Original\cdm\cdm\data\cdm_bak.mdb";

    BACKUP_ROOTPATH = @"F:\backup"

    I want to replace ROOTPATH with BACKUP_ROOTPATH from filepath to get new_filepath;

    I tried it like following;

    public static string GetBackupPath(string file)
    {
        string backupfilepath = "";
        string tempstr = "";
        tempstr = file.Replace(ROOTPATH, "");
        backupfilepath = Path.Combine(BACKUP_ROOTPATH, tempstr);
        return (backupfilepath);
    }

    If I run this, tempstr become @"\cdm\cdm\data\cdm_bak.mdb".

    When it is combined in Path.Combine(BACKUO_ROOT, tempstr), it returns @"\cdm\cdm\data\cdm_bak.mdb", not @"F:\backup\cdm\cdm\data\cdm_bak.mdb".

    In case filepath =@"C:\cdm\cdm\data\cdm_bak.mdb", GetBackupPath returns correct path but not in case filepath =@"D:\Original\cdm\cdm\data\cdm_bak.mdb".

    How do I make it work in any case?

    Tuesday, May 29, 2018 9:56 PM

All replies

  • Hello,

     Try using the following code and see if this is a solution;

    filepath = filepath.Replace( ROOTPATH, BACKUP_ROOTPATH );
     

     Hope this helps :)

    Tuesday, May 29, 2018 10:29 PM
  • Hi Jeff0803,

    Two ways to get the path you want.

    1. Please try the code below. You miss \ in your ROOTPATH.

      static void Main(string[] args)
            {
                string filepath = @"D:\Original\cdm\cdm\data\cdm_bak.mdb";
                GetBackupPath(filepath);
    
            }
            public static string GetBackupPath(string file)
            {
                string ROOTPATH = @"D:\Original\";
                string BACKUP_ROOTPATH = @"F:\backup";
                string backupfilepath = "";
                string tempstr = "";
                tempstr = file.Replace(ROOTPATH, "");
                backupfilepath = Path.Combine(BACKUP_ROOTPATH, tempstr);
                return (backupfilepath);
            }

    2. In addition, according to the reply from User3DX, I make a simple example for your reference.

        string ROOTPATH = @"D:\Original";
                string filepath = @"D:\Original\cdm\cdm\data\cdm_bak.mdb";
                string BACKUP_ROOTPATH = @"F:\backup";
                string tempstr = filepath.Replace(ROOTPATH, BACKUP_ROOTPATH);

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, May 31, 2018 3:03 AM
    Moderator