本文介绍了2016年9月/2016年10月Windows 10更新1607后,在C#中禁用ICS(Internet连接共享)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在Windows 7、8、8.1和10(旧版本)中使用这样的代码. Windows中的某些内容随着最新更新而发生了变化,并且现在引发了System.AccessViolationException异常.

I've been using code like this for Windows 7, 8, 8.1,  and 10 (older versions)   Something in windows changed with the latest update and now a System.AccessViolationException  gets thrown.

现在我看到此异常:

Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
   at IDispatchInvoke(IntPtr , Int32 , INVOKEKIND , DISPPARAMS& , Variant& , ExcepInfo& , UInt32& )
   at System.Management.Automation.ComInterop.UnsafeMethods.IDispatchInvoke(IntPtr dispatchPointer, Int32 memberDispId, INVOKEKIND flags, DISPPARAMS& dispParams, Variant& result, ExcepInfo& excepInfo, UInt32& argErr)
   at CallSite.Target(Closure , CallSite , ComObject )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at System.Management.Automation.Interpreter.DynamicInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.Interpreter.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.LightLambda.RunVoid1[T0](T0 arg0)
   at System.Management.Automation.DlrScriptCommandProcessor.RunClause(Action`1 clause, Object dollarUnderbar, Object inputToProcess)
   at System.Management.Automation.DlrScriptCommandProcessor.Complete()
   at System.Management.Automation.CommandProcessorBase.DoComplete()
   at System.Management.Automation.Internal.PipelineProcessor.DoCompleteCore(CommandProcessorBase commandRequestingUpstreamCommandsToStop)
   at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
   at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper()
   at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

我的测试代码基于:

https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Management.Automation;
using System.Collections.ObjectModel;

namespace PowerShellExecutionSample
{
    class Program
    {

        private static string getPowerShellScript(String Interface_ID)
        {
            String script_pattern = @"
# Register the HNetCfg library;
regsvr32 /s hnetcfg.dll;
# Get sharing configuration;
$INTERFACE_ID = ""{0}"";
";
            String script = string.Format(script_pattern, Interface_ID);

            script += @"
Write-Output ""INTF ID $INTERFACE_ID "";
# Create a NetSharingManager object
$My_NetShare = New-Object -ComObject HNetCfg.HNetShare;
Write-Output $My_NetShare
Write-Output ""INSTALLED $My_NetShare.SharingInstalled""

if($MY_NetShare.SharingInstalled){
Write-Output ""Sharing Installed:  $MY_NetShare.SharingInstalled "";
	if($Con = $MY_NetShare.EnumEveryConnection | ? { $MY_NetShare.NetConnectionProps.Invoke($_).Guid -eq $INTERFACE_ID }){
		$Sharing_Config = $MY_NetShare.INetSharingConfigurationForINetConnection.Invoke($Con);
		if($Sharing_Config.SharingEnabled){
            Write-Output ""calling DisableSharing"";
			$Sharing_Config.DisableSharing();
            Write-Output ""Done DisableSharing""
        }else{
			Write-Output ""not enabled"";
        }
   	}else{
		Write-Output ""no connections"";
   	}
}else{
	Write-Output ""not installed"";
}
Write-Output ""Done PowerShell"";
";
            return script;
        }
        public static string GetScriptTmpFile(String Interface_ID)
        {
            string myTempFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "Disable-ICS.ps1");
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(myTempFile))
            {
                sw.WriteLine(getPowerShellScript(Interface_ID));
            }
            return myTempFile;
        }

        public static void DisableICS(String Interface_ID)
        {

            using (PowerShell PowerShellInstance = PowerShell.Create())
            {

                String script = getPowerShellScript(Interface_ID);

                PowerShellInstance.AddScript(script);

                // invoke execution on the pipeline (collecting output)
                Collection<PSObject> PSOutput = PowerShellInstance.Invoke();

                // check the other output streams (for example, the error stream)
                if (PowerShellInstance.Streams.Error.Count > 0)
                {
                    // error records were written to the error stream.
                    // do something with the items found.
                    Console.WriteLine("Error in DisableICS");

                }

                // loop through each output object item
                foreach (PSObject outputItem in PSOutput)
                {
                    // if null object was dumped to the pipeline during the script then a null
                    // object may be present here. check for null to prevent potential NRE.
                    if (outputItem != null)
                    {
                        //TODO: do something with the output item
      //                  Console.WriteLine(outputItem.BaseObject.GetType().FullName);
                        Console.WriteLine(outputItem.BaseObject.ToString() + "\n");
                    }
                }
            }
        }
        /*
        public static void DisableICS_Exec(String Interface_ID)
        {
            string myTempFile = GetScriptTmpFile(Interface_ID);


            Console.WriteLine("Tmp file " + myTempFile);
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "PowerShell.exe";
            startInfo.Arguments = " -ExecutionPolicy UnRestricted -File " + myTempFile;
            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;
            process.StartInfo = startInfo;
            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            Console.WriteLine("PS Output: " + output);
        }
        */

        public static bool IsAdministrator()
        {
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
            return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }

        static void Main(string[] args)
        {
            if (!IsAdministrator()) {
                Console.WriteLine("Rerun this test as admin.  ICS changes can only be done by admin.");
                Console.ReadKey();
                return;
            }

            System.Net.NetworkInformation.NetworkInterface[] interfaces;

            interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            foreach (System.Net.NetworkInformation.NetworkInterface nic in interfaces)
            {

                if (!nic.Supports(System.Net.NetworkInformation.NetworkInterfaceComponent.IPv4))
                    continue;
                if (!(nic.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Ethernet
                        || nic.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Wireless80211
                        || nic.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.GigabitEthernet))
                    continue;


                System.Net.NetworkInformation.IPInterfaceProperties ipProps = nic.GetIPProperties();
                System.Net.NetworkInformation.UnicastIPAddressInformationCollection uniCast = ipProps.UnicastAddresses;

                if (uniCast == null)
                {
                    // no address
                    continue;
                }
                Console.WriteLine("------------");

                Console.WriteLine("interface: " + nic.Name + "  Desc: " + nic.Description + " Status:" + nic.OperationalStatus.ToString());
                Console.WriteLine("interface ID: " + nic.Id);

                try
                {
                    DisableICS(nic.Id);
                   // DisableICS_Exec(nic.Id);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception" + ex.ToString());
                }

            }
            Console.WriteLine("Done");
            Console.ReadKey();
        }
    }

}

我将完整的Visual Studio C#项目放置在:

I've placed the complete Visual studio C# project at:

https://1drv.ms/u/s!AsK6b4DnsWx_jRyrDqMl9qJzbfIM

https://1drv.ms/u/s!AsK6b4DnsWx_jRyrDqMl9qJzbfIM

看到相同内容的其他用户的其他上下文:

Additional context of other users seeing the same thing:

https://github.com/utapyngo/icsmanager/issues/10

https://github.com/utapyngo/icsmanager/issues/10

推荐答案

1.当然,作者 弄乱了Pointer的方法论.否则您将不再提交有效的输入.

1. The writer of course messed up the Pointer arythmethic. Or you no longer hand in valid input.

2.磁盘上或复制到内存中的文件具有二进制级别的损坏.

2. The file on the disk or after copied into memory has binary level damage.

3.二元性问题.托管代码不可知.不受管理永远不可能.如果二进制不匹配,则可能发生这种情况.

3. Binarity issue. Managed code is bitness agnostic. Unmanaged never can be. If binarity missmatches, this can happen.

4.第三方干扰.去年,AVG 2015就是这样的一个,几乎所有其他WindowsForms程序都崩溃了.必须是Virus Scanner级别上的某项 更深.

4. 3rd Party interference. We had that one last year with AVG 2015 crashing just about any other WindowsForms programm like this. Must be something on the Virus Scanner level  deeper.

我们需要知道发生这种情况的精确线.另外,通过关闭病毒扫描程序检查拼写,以检查第三方天使.

We would need to know wich precise line this happens on. Also check the 3rd Party angel by turning off the Virus scanner for a spell.


这篇关于2016年9月/2016年10月Windows 10更新1607后,在C#中禁用ICS(Internet连接共享)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 11:28