如何使用 Windows shell API 和 C# 更改映射驱动器的友好名称?我的实际问题是我正在处理一个没有 UNC 路径的断开连接的网络驱动器,因此重命名它的唯一方法是从资源管理器,但我想以编程方式进行。
3 回答
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.
System.IO.DriveInfo有一个属性VolumeLabel,可让您更改卷上的标签。查看 VolumeLabel 上的异常和备注,了解重命名卷的要求。
除非您将其映射为网络驱动器,否则您似乎无法彻底重命名 UNC。您还可以创建 UNC 的快捷方式并重命名它。
您应该使用SetVolumeLabel
API。
基本上,您所指的驱动器的“名称”称为卷标。您可以 P/Invoke API 并以这种方式进行更改。
要获取扩展的错误信息,您可以使用GetLastError
.