Rename a mapped drive with shell API

荒凉一梦 提交于 2019-12-23 17:34:48

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7079264/rename-a-mapped-drive-with-shell-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!