您的位置:首页 > 理论基础 > 计算机网络

C#实现启用或停用本地网络连接,转

2009-05-15 14:58 369 查看
http://blog.csdn.net/ojlovecd/archive/2009/02/28/3945605.aspx

首先添加Microsoft Shell Control And Automation引用,

using System;
using System.Threading;

class test
{
static void Main(string[] args)
{
NetWork("本地连接", "启用");
}
/// <summary>
/// 实现启用或停用本地网络链接
/// </summary>
/// <param name="netWorkName">本地连接名称</param>
/// <param name="operation">操作,传入“启用”或“停用”</param>
static void NetWork(string netWorkName, string operation)
{
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(49);
foreach (Shell32.FolderItem fi in folder.Items())
{
if (fi.Name != netWorkName)
continue;
Shell32.ShellFolderItem folderItem = (Shell32.ShellFolderItem)fi;
foreach (Shell32.FolderItemVerb fiv in folderItem.Verbs())
{
if (!fiv.Name.Contains(operation))
continue;
else
{
fiv.DoIt();
Thread.Sleep(1000);
break;
}
}
}
}
}

代码说明:

NetWork方法的两个参数说明:第一个为要进行操作的本地连接名称,第二个为你要进行的操作,传入“启用”或“停用”(win2000下可能是“禁用”)

这个方法的原理是先找到“网络连接”这个虚拟文件夹,其中shell.NameSpace(49)中的49据说是为了避免遍历控制面板,我没有测试过,有兴趣的朋友可以试试。然后找到要控制的本地连接对应的folderitem,然后枚举verb,找到需要的verb后,调用verb的DoIt方法,在DoIt的时候加了一个Thread.Sleep(1000);是为了使程序不会由于遍历的太快而使操作失效,上述方法已测试通过,如有不足之处请指出,参考资料:

http://www.cnblogs.com/rainstormmaster/archive/2006/02/11/328943.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: