开发者

Access internal field [WebClient]

I have a WebClient instance that receives data from a remote website. I referenced a DownloadProgressChanged event handler and I am trying to access InnerBuffer, which is an internal field in the DownloadBitsState nested class (set as private) in WebClient.

I am using the following code right in the DownloadProgressChanged event handler:

WebClient c = (WebClient)sender;
Type t = typeof(WebClient).GetNestedType("DownloadBitsState", BindingFlags.NonPublic);

FieldInfo m = t.GetField("InnerBuffer",BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

Debug.WriteLine(m.GetValue(c).ToString());

I get a runtime error: FieldAccessException (System.Net.开发者_如何学PythonWebClient+DownloadBitsState.InnerBuffer)

Is there any way I can read this field or I simply cannot read the contents of internal fields?


The instance is incorrect.

You cannot pass a WebClient type instance when the FieldInfo expects a DownloadBitsState instance.


It's possible that the field you want is write only. Use reflector to look at the source to see what is going on. If it's write only then you will need to access the private field.

Also: He IS passing in the reference using m.GetValue(c) as c is the instance of sender cast as Webclient.

BTW: Make sure WebClient is not null.

--Edit: After posting my answer I realize that you're trying to access a property of a type that isnt instantiated. Doh! Does Webclient have a property that has an instance of DownloadBitsState? Use that, THEN pull the property

--Edit: Looking at the code, the only method in webclient that instantiates DownloadBitsState is private byte[] DownloadBits()

private byte[] DownloadBits(WebRequest request, Stream writeStream, CompletionDelegate completionDelegate, AsyncOperation asyncOp)
{
    WebResponse response = null;
    DownloadBitsState state = new DownloadBitsState(request, writeStream, completionDelegate, asyncOp, this.m_Progress, this);
    if (state.Async)
    {
        request.BeginGetResponse(new AsyncCallback(WebClient.DownloadBitsResponseCallback), state);
        return null;
    }
    response = this.m_WebResponse = this.GetWebResponse(request);
    int bytesRetrieved = state.SetResponse(response);
    while (!state.RetrieveBytes(ref bytesRetrieved))
    {
    }
    state.Close();
    return state.InnerBuffer;
}

So, you can't really do what you want in the way you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜