Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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\

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading