我写了一个程序来监控IMAP电子邮件账户。它按计划在我随身携带的笔记本电脑上运行。有时,当我的互联网连接是通过移动设备时(即,我按GB计费),它也会运行,但我不希望它这样做,因为它会使用大量带宽,所以可以等到带宽空闲再运行。
那么问题来了:.NET程序如何确定它正在使用的连接是否是按流量计费的?
我写了一个程序来监控IMAP电子邮件账户。它按计划在我随身携带的笔记本电脑上运行。有时,当我的互联网连接是通过移动设备时(即,我按GB计费),它也会运行,但我不希望它这样做,因为它会使用大量带宽,所以可以等到带宽空闲再运行。
那么问题来了:.NET程序如何确定它正在使用的连接是否是按流量计费的?
在MSDN上进行简要搜索,找到了NetworkInformation.GetInternetConnectionProfile函数。它似乎是Metro界面的正式部分,但我听说桌面应用程序可以访问大多数Metro库。
$definition = @"
using System;
using System.Runtime.InteropServices;
namespace Win32Api
{
public class NtDll
{
[DllImport("ntdll.dll", EntryPoint="RtlAdjustPrivilege")]
public static extern int RtlAdjustPrivilege(ulong Privilege, bool Enable, bool CurrentThread, ref bool Enabled);
}
}
"@
Add-Type -TypeDefinition $definition -PassThru | Out-Null
[Win32Api.NtDll]::RtlAdjustPrivilege(9, $true, $false, [ref]$false) | Out-Null
#Setting ownership to Administrators
$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\DefaultMediaCost",[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,[System.Security.AccessControl.RegistryRights]::takeownership)
$acl = $key.GetAccessControl()
# Use your account "Administrators" or any other which is actually an existing one on your account
$acl.SetOwner([System.Security.Principal.NTAccount]"Administrators")
$key.SetAccessControl($acl)
#Giving Administrators full control to the key
$rule = New-Object System.Security.AccessControl.RegistryAccessRule ([System.Security.Principal.NTAccount]"Administrators","FullControl","Allow")
$acl.SetAccessRule($rule)
$key.SetAccessControl($acl)
$path = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\DefaultMediaCost"
# you can check for "Ethernet" "Wifi" "4G" etc.
$name = "Ethernet"
#If the Value is 2 = metered
New-ItemProperty -Path $path -Name $name -Value "2" -PropertyType DWORD -Force | Out-Null
Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity references could not be translated.".