Here I will post problems I and my colleagues met and solutions we found.

Sunday, April 27, 2008

How to browse for computer name

I never thought that a simple task of browsing for a computer name would be such a pain. Nevertheless it was.

What I need is to give user the dialog to choose computer from his local network.

First step:
WPF does not have FolderBrowser dialog. Well, we can use Windows.Forms for that. The have FolderBrowserDialog.

Step two:
In my dialog I wanted to start search from "Network". FolderBrowserDialog has RootFolder property for that. But enumeration does not support Network folder. I don't know why they removed it, because technically all they had to do is to add one enumeration value with proper value setting. So, that was the first obstacle.

Step three:
Doing some research I found class System.Windows.Forms.Design.FolderNameEditor from System.Design.dll. It's not perfect, but I could make it work easily and this one could start from folder Network. However, when I did that the return value was empty string.

Step four:
I started to research again. Now I found that Win32 method SHBrowseForFolder that is actually called behind the scene, returns computer name in very weird way. It retuns it not where directory path is usually returned, but in field name displayname. And that, for sure, was not handled properly in this System.Windows.Forms.Design.FolderNameEditor class.

Step five:
I researched some more and found a component ShellFolderBrowser at CodeProject. Now guess what? It didn't have RootFolder. So, I was where I started from.

Step six:
I decided that I researched enough. At this point it become faster for me to just write some code. Since there are plenty of classes that can support folder browsing in general, I decided not to write "universal" component or something like that. I just wrote simple method to choose computer name. It was based on ShellFolderBrowser I found at CodeProject (Author: Rama Krishna Vavilala) and some rip off from System.Windows.Forms.Design.FolderNameEditor extracted using Reflector.

It's draft, simple and not pretending to be component for general use. However, if you are interested, you can download the code from here ComputerBrowserZip. Again, you can learn more from looking at .NET code by Reflector or to ShellFolderBrowser.

1 comment:

Anonymous said...

Thanks for this. It is just what I needed. I tweeked it a little and made the Title and DisplayName public properties. It really shouldn't be this hard as you said and I'm glad I ran into your post before going through the same steps you did.