How can I change the friendly name of a mapped drive using the Windows shell API and C#? My actual problem is that I am dealing with a disconected network drive without a UNC path, so the only way to rename it is from Explorer, but I want to do that programmatically.Answer1:
I had a similar problem and solved it using the following code:
Shell32.Shell shell = new Shell32.Shell(); ((Shell32.Folder2)shell.NameSpace("X:")).Self.Name = "Friendly Label";
With a reference to COM --> Microsoft Shell Controls and Automation. It is basically the C# representation of an old VBS Code I had
Set oShell = CreateObject("Shell.Application") oShell.NameSpace("X:").Self.Name = "Friendly Label"
The difference however is that the C# implementation of NameSpace for some reason returns a <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb787868(v=vs.85).aspx" rel="nofollow">folder object</a> while all VB implementations seem to return a <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb787854(v=vs.85).aspx" rel="nofollow">folder2 object</a>. Only the folder2 has the 'Self' property, so the additional cast is needed.
Also, as was pointed out in one of the comments, this only works within an STA apartment, so the Main() method has to be decorated with [STAThread].
I hope it's not bad practice to answer such old questions, but I was quite frustrated to not find a solution to this anywhere.Answer2:
You should use the <a href="http://msdn.microsoft.com/en-us/library/aa365560.aspx" rel="nofollow">
Basically, the drive's "name" that you're referring to is called the Volume Label. You could P/Invoke the API and change it that way.
To get extended error information, you can use <a href="http://msdn.microsoft.com/en-us/library/ms679360.aspx" rel="nofollow">
<a href="http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx" rel="nofollow">System.IO.DriveInfo</a> has a property <a href="http://msdn.microsoft.com/en-us/library/system.io.driveinfo.volumelabel.aspx" rel="nofollow">VolumeLabel</a> that lets you change the label on your volumes. Check the exceptions and remarks on VolumeLabel to see the requirements for renaming a volume.
It looks like you can't outright rename the UNC unless you map it as a network drive. You could also create a shortcut to the UNC and rename that as well.