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

首先添加Microsoft Shell Control And Automation引用,如果你不知道怎么添加Microsoft Shell Control And Automation引用,请参考一下步骤:
在你的解决方案资源管理器的bin上右键->选择添加引用->选择->COM标签->找到这个引用按确定即可

然后就可以编写代码了:



+ expand sourceview plaincopy to clipboardprint?
static void Main(string[] args)
{
NetWork("本地连接", "启用");
}
///
/// 实现启用或停用本地网络链接
///

/// 本地连接名称
/// 操作,传入“启用”或“停用”
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;
}
}
}
}
static void Main(string[] args)
{
NetWork("本地连接", "启用");
}
///
/// 实现启用或停用本地网络链接
///

/// 本地连接名称
/// 操作,传入“启用”或“停用”
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); 是为了使程序不会由于遍历的太快而使操作失效,上述方法已测试通过,如有不足之处请指出.

posted on 2009-10-20 09:53  pp-dotnet  阅读(118)  评论(0)    收藏  举报

导航