2013-01-04 55 views
1

我正在使用Windows Server 2008,並且希望獲得DNS服務器。所以我認爲最快的方法應該是執行ipconfig,然後使用TProcess解析它的輸出。當使用TProcess運行時,控制檯應用程序永遠不會返回

我已經想出了這個代碼:

var 
    proces : TProcess; 
    begin 
    ... 
    proces := TProcess.Create(nil); 
    proces.Executable := 'ipconfig'; 
    proces.Options := proces.Options + [poWaitOnExit,poUsePipes]; 
    try 
    proces.Execute; 
    except 
     proces.Free; 
    end; 
    SetLength(rez,proces.Output.NumBytesAvailable); 
    proces.Output.Read(rez[1],proces.Output.NumBytesAvailable); 
    ShowMessage(rez); 

代碼作品,但之後我手動關閉window.I試圖poNoConsole控制檯但還是同樣的結果,過程IPCONFIG保持在任務管理器活躍。

爲什麼控制檯應用程序ipconfig終止?如果我運行它,它會在吐出標準輸出信息後退出。

這是我的配置嗎?這是一個錯誤嗎?幫幫我!謝謝:)

回答

1

由於ipconfig可以生成很多輸出,所以不要試圖一次讀取它,請使用wiki中的Reading large output方法。

FPC(2.6.2)的下一個迭代將包含大量的runcommand過程,這些過程用於處理一系列常見情況的過程並將輸出返回到單個字符串中。

注API的解決方案也是可能的:

{$mode delphi} 

uses JwaIpExport, JwaIpRtrMib, JwaIpTypes,jwawinerror,classes,jwaiphlpapi; 

procedure GetDNSServers(AList: TStringList); 
var 
    pFI: PFixed_Info; 
    pIPAddr: PIPAddrString; 
    OutLen: Cardinal; 
begin 
    AList.Clear; 
    OutLen := SizeOf(TFixedInfo); 
    GetMem(pFI, SizeOf(TFixedInfo)); 
    try 
    if GetNetworkParams(pFI, OutLen) = ERROR_BUFFER_OVERFLOW then 
    begin 
     ReallocMem(pFI, OutLen); 
     if GetNetworkParams(pFI, OutLen) <> NO_ERROR then Exit; 
    end; 
    // If there is no network available there may be no DNS servers defined 
    if pFI^.DnsServerList.IpAddress.s[0] = #0 then Exit; 
    // Add first server 
    AList.Add(pFI^.DnsServerList.IpAddress.s); 
    // Add rest of servers 
    pIPAddr := pFI^.DnsServerList.Next; 
    while Assigned(pIPAddr) do 
    begin 
     AList.Add(pIPAddr^.IpAddress.s); 
     pIPAddr := pIPAddr^.Next; 
    end; 
    finally 
    FreeMem(pFI); 
    end; 
end; 

var v : TStringList; 
    s : string; 
begin 
v:=tstringlist.create; 
getdnsservers(v); 
for s in v do writeln(s); // this probably requires 2.6+ 
v.free; 
end. 
+0

非常感謝,讓sense.FPC是美妙的:d – opc0de

+1

注意,API版本使用了不/少64位Windows驗證JWA單位。 –

相關問題