Rename a mapped drive with shell API
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 Explor开发者_如何学Pythoner, but I want to do that programmatically.
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 folder object while all VB implementations seem to return a folder2 object. 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.
You should use the SetVolumeLabel
API.
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 GetLastError
.
System.IO.DriveInfo has a property VolumeLabel 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.
精彩评论