Execute Root Commands and read output Xamarin

為{幸葍}努か 提交于 2021-01-04 05:35:30

问题


I can't read the file from the root directory. How to do it? I use the command for reading

Java.Lang.Process suProcess =  Java.Lang.Runtime.GetRuntime().Exec(new string[] { "su", "-c", "cat /data/misc/vpn/state" });

but how do I get an answer?


回答1:


The Java.Lang.Process class has some interesting Streams you will need to read from. InputStream and ErrorStream.

First of all, after you have created your process, you will need to wait for it. This can be done nicely with .WaitForAsync(). This will allow you to answer any dialogs etc. that usually come up when asking for root permissions.

When .WaitForAsync() returns it gives you an Exit Code. 0 means everything went well any other Exit Code means that there probably was an error.

In the case of Exit Code 0, you can probably read from the InputStream and get what you are looking for.

So you code would end up looking something like:

async Task<string> GetVpnStatus()
{
    var process = Java.Lang.Runtime.GetRuntime().Exec(new string[] { "su", "-c", "cat /data/misc/vpn/state" });
    var exitCode = await process.WaitForAsync();

    if (exitCode == 0)
    {
        using (var outputStreamReader = new StreamReader(process.InputStream))
            return await outputStreamReader.ReadToEndAsync();
    }

    if (process.ErrorStream != null)
    {
        using (var errorStreamReader = new StreamReader(process.ErrorStream))
            return await errorStreamReader.ReadToEndAsync();
    }

    return null;
}

The result of this will look something like

ppp0
10.0.0.42/32
0.0.0.0/0
105.112.3.1 123.234.12.55


来源:https://stackoverflow.com/questions/50934376/execute-root-commands-and-read-output-xamarin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!