Rename Datalake File Using C#


//Connectionstring  : Datalake connection string
//path : "ContainerName/folder1/test1.txt"
//newFileName : "test2.txt"

public void RenameContainerFileName(string connectionString, string path,string newFileName)
{
    var storageAccount = new DataLakeServiceClient(connectionString);
    string[] strPath = path.Split("/");
    string container = string.Empty;
    string newFoldername = string.Empty;
    DataLakeFileSystemClient dirClient = storageAccount.GetFileSystemClient(strPath[0]);
    if (strPath.Length == 2) //Container inside file "ContainerName/test1.txt"
    {
        DataLakeFileClient filClient = dirClient.GetFileClient(strPath[1]);
        filClient.Rename(newFileName);
        
    }
    else
    {
        DataLakeDirectoryClient directory = dirClient.GetDirectoryClient(strPath[1]);
        if (strPath.Length == 3) // Container inside folder file "ContainerName/folder1/test1.txt"
        {
            DataLakeFileClient filClient = directory.GetFileClient(strPath[2]);
            filClient.Rename( strPath[1]  + '/' + newFileName); 
        }
        else
        {
     //Multi level datalake folder file "ContainerName/folder1/folder2/folder3/test1.txt"
            int i = 0;
            foreach (string str in strPath)
            {
                i++;
                if (i > 2 && i < strPath.Length)
                {
                    container = container + str + ((i + 1 == strPath.Length) ? "" : "/");
                }
                if (i == strPath.Length)
                    newFoldername = str;
            }
            DataLakeDirectoryClient subdirectory = directory.GetSubDirectoryClient(container);
            DataLakeFileClient filClient = subdirectory.GetFileClient(newFoldername);
            filClient.Rename(container + '/' + newFileName);
        }
       }    
}