使用 shell API 重命名映射驱动器 [英] Rename a mapped drive with shell API

查看:28
本文介绍了使用 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.

推荐答案

我遇到了类似的问题,使用以下代码解决了:

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";

参考 COM --> Microsoft Shell 控件和自动化.它基本上是我拥有的旧 VBS 代码的 C# 表示

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"

然而,不同之处在于 NameSpace 的 C# 实现出于某种原因返回了一个 文件夹对象 而所有 VB 实现似乎都返回一个 folder2 对象.只有 folder2 有 'Self' 属性,所以需要额外的转换.

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.

此外,正如其中一条评论所指出的,这仅适用于 STA 单元,因此必须使用 [STAThread] 修饰 Main() 方法.

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.

这篇关于使用 shell API 重命名映射驱动器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆