使用 shell API 重命名映射驱动器
如何使用 Windows shell API 和 C# 更改映射驱动器的友好名称?我的实际问题是,我正在处理一个没有 UNC 路径的断开连接的网络驱动器,因此重命名它的唯一方法是从资源管理器中,但我想以编程方式执行此操作。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我遇到了类似的问题,并使用以下代码解决了它:
参考 COM --> Microsoft Shell 控制和自动化。
它基本上是我拥有的旧 VBS 代码的 C# 表示形式
,但区别在于命名空间的 C# 实现由于某种原因返回 文件夹对象 而所有 VB 实现似乎都返回 folder2 对象。只有folder2具有“Self”属性,因此需要额外的转换。
另外,正如评论之一所指出的,这只适用于 STA 公寓,因此 Main() 方法必须用 [STAThread] 进行修饰。
我希望回答这些老问题不是坏习惯,但我很沮丧,因为在任何地方都找不到解决方案。
I had a similar problem and solved it using the following code:
With a reference to COM --> Microsoft Shell Controls and Automation.
It is basically the C# representation of an old VBS Code I had
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.
您应该使用
SetVolumeLabel
API。基本上,您所指的驱动器的“名称”称为卷标。您可以 P/Invoke API 并以这种方式更改它。
要获取扩展错误信息,您可以使用
GetLastError
。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 有一个属性 VolumeLabel 可让您更改卷上的标签。检查 VolumeLabel 上的例外和备注,了解重命名卷的要求。
看起来您无法彻底重命名 UNC,除非您将其映射为网络驱动器。您还可以创建 UNC 的快捷方式并重命名它。
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.