FolderBrowserDialog split vs2019 to vs2010

Hi is there anyone know why this code not working in vs2010 but works in vs2019

textBox1.Text =  folderBrowserDialog1.SelectedPath.Split(@"\")[^2];

What I am trying to do is i want to display selected folder name in the textbox.

Example: C:\Test\Test1\Test2\

In my textbox it will display Test1 folder name based on the code.
so this code above is working in vs2019 but i want also to work in vs2010

>Solution :

You cannot use [^2]; in any but very recent versions of C#. Prior to that feature being added, we had to get the length of the list and then calculate the actual index of the item based on that, so that’s what you’ll have to do if you want code that will work in all versions.

That said, I wouldn’t be using Split anyway. You should use the Path class to manipulate file and folder paths. It would be less succinct but more appropriate to do this:

var selectedPath = folderBrowserDialog1.SelectedPath;
var parentPath = Path.GetDirectoryName(selectedPath);
var parentName = Path.GetFileName(parentPath);

textBox1.Text = parentName;

You can collapse that if you want:

textBox1.Text = Path.GetFileName(Path.GetDirectoryName(folderBrowserDialog1.SelectedPath));

Leave a Reply