我正在製作一個爲您製作Wi-Fi熱點的程序,並使用PowerShell腳本自動啓用Internet連接共享。正在運行Powershell腳本導致'內存損壞'或'無法讀取或寫入'
腳本工作和運行完美,但我必須等待它完成,所以我可以通知用戶完成。即時通訊使用下面的代碼,雖然工作,但...
但它崩潰,並導致我的家庭電腦上分配更快的錯誤。 我得到一個無法讀取或寫入或內存是腐敗的錯誤,我不能真正解釋。
public static void ToggleIcs(string connectionInterface, bool state)
{
string toggle;
string par1;
string par2;
if (state){
toggle = "EnableSharing";
par1 = "0";
par2 = "1";
}else{
toggle = "DisableSharing";
par1 = "";
par2 = "";
}
using (PowerShell powerShellInstance = PowerShell.Create())
{
// this script enables or disables internet sharing with the connectionInterface given.
powerShellInstance.AddScript("" +
"regsvr32 hnetcfg.dll /s;" +
"$m = New-Object -ComObject HNetCfg.HNetShare;" +
"$m.EnumEveryConnection |% { $m.NetConnectionProps.Invoke($_) };" +
"$c = $m.EnumEveryConnection |? { $m.NetConnectionProps.Invoke($_).Name -eq '" + connectionInterface + "' };" +
"$config = $m.INetSharingConfigurationForINetConnection.Invoke($c);" +
"Write-Output $config.SharingEnabled;" +
"Write-Output $config.SharingConnectionType;" +
"$config." + toggle + "(" + par1 + ");" +
"$m2 = New-Object -ComObject HNetCfg.HNetShare;" +
"$m2.EnumEveryConnection |% { $m2.NetConnectionProps.Invoke($_) };" +
"$c2 = $m2.EnumEveryConnection |? { $m2.NetConnectionProps.Invoke($_).DeviceName -Match 'Microsoft Hosted Network Virtual Adapter' };" +
"$config2 = $m2.INetSharingConfigurationForINetConnection.Invoke($c2);" +
"Write-Output $config2.SharingEnabled;" +
"Write-Output $config2.SharingConnectionType;" +
"$config." + toggle + "(" + par2 + ");");
PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
IAsyncResult result = powerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
Console.WriteLine(DateTime.Now + ">> Started Powershell script");
int i = 0;
while (!result.IsCompleted)
{
if (i < 60)
{
Console.WriteLine(DateTime.Now + ">> Running script");
}
else
{
ScriptFailed();
powerShellInstance.Stop();
break;
}
i++;
Thread.Sleep(1000);
}
Console.WriteLine(DateTime.Now + ">> Executed Internet Sharing script");
}
}
這是錯誤即時得到:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
我沒有得到這樣一行它崩潰,但它Thread.Sleep(1000);
後崩潰。我發現使用斷點
正如我所說,腳本在我的筆記本電腦上運行良好,它可以在我的快速計算機上工作,但一旦碰到Thread.Sleep(1000)
就會崩潰。 崩潰後,我檢查是否在網絡和共享中心啓用了ICS,並且它是正確的。
我試圖刪除Thread.Sleep(1000);
,但之後它崩潰了。
我可以嘗試或做不同的事情?
編輯
我沒有堆棧跟蹤然而,正如我在我的電腦更快它崩潰的不是我。但我會盡快發佈。
編輯
正如TheLethalCoder提到的,這可能是因爲我試圖存取權限IsCompleted
雖然正在更新。如果這就是它發生的原因,我將如何檢查它是否被修改或等待它完成。
編輯
正如我真的不知道該調用堆棧是什麼,或者什麼是堆棧跟蹤,以及如何我可以用它生病提供什麼,我在飛機墜毀前看到了一個瞬間的圖像。
編輯 我做了一些周圍窺探,發現了一些東西我試過了。
首先,在應用程序屬性 - >構建中,我勾選了「首選32位」關閉 因爲有些人用這個問題解決了他們的問題。而且我沒有崩潰,但腳本也無法運行,導致我的互聯網連接丟失。
所以我打開了它。 我也嘗試了netsh winsock reset
命令並重新啓動我的電腦,但它仍然崩潰。
我現在所有的線索都沒有了,但是我通過尋找答案來發布這兩個東西,也許這將起作用。
什麼是完整錯誤(包括堆棧跟蹤)? – Richard
我還沒有得到,因爲我現在正在工作,它在這臺機器上工作正常,但我會盡快發佈 – Jeremy
看到這個錯誤表明發生了'不安全'代碼內發生的事情,你不使用'unsafe '代碼我相信它比C#代碼更能處理腳本。 – TheLethalCoder