我正在编写一个小引擎来从一些 .php 文件中下载文本,我已经在 Visual c# 中完成了这个引擎并且我没有遇到问题。
我正在这样做:
[ ... ]
WebClient client = null;
try {
client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler( CompleteDownload );
client.AllowReadStreamBuffering = true;
client.DownloadStringAsync( new Uri( "http://blabla/bla.php" ) );
}
catch (Exception e) {
lbl1.Text = e.Message;
}
[ ... ]
这可以“捕获”下载的数据:
public void CompleteDownloadPcops( object sender, DownloadStringCompletedEventArgs ea ) {
if ( ea.Error == null ) {
try{
lbl1.Text = ea.Result;
}
catch(Exception e) {
lbl2.Text = e.Message;
}
}
}
执行这段代码,我得到了inlbl1
的异常Exception has been thrown by the target of an invocation
结果。为什么?而且,在知道原因之后,我该如何解决呢?lbl1.Text = ea.Result;
CompleteDownload
更多信息:我在 Ubuntu 11.04 平台上的 monodevelop 2.4 中使用月光。
更新
根据您的推荐,我已将系统更新为 MonoDevelop 2.6。现在,做同样的事情,我在ea.Error
. 消息是(西班牙语):
System.Security.SecurityException ---> System.Security.SecurityException: Error de seguridad.
en System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
en System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
en System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__1(Object sendState)
--- Fin del seguimiento de la pila de excepciones internas ---
en System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
en System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
en System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
en System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
.
我现在使用的完整代码是:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
WebClient client = null;
try
{
client = new WebClient();
client.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.AllowReadStreamBuffering = true;
client.DownloadStringAsync(new Uri("http://carles.lambdafunction.com/a/try.php"));
}
catch (Exception ex)
{
lbl1.Text = ex.Message;
btn1.Content = "A";
}
}
void client_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
lbl2.Text = e.Result;
}
catch (Exception ex)
{
lbl1.Text = ex.Message;
lbl2.Text = ex.InnerException.ToString();
btn1.Content = "C";
}
}
else
{
lbl1.Text = e.Error.ToString();
btn1.Content = "B";
txt1.Text = e.Error.ToString();
}
}
}
您可以看到网络调用的输出(到虚拟页面/p/try.php),这真的很简单。真的,现在,我迷路了,因为我正在学习本教程:http ://weblogs.asp.net/scottgu/pages/silverlight-tutorial-part-3-using-networking-to-retrieve-data-and-填充-a-datagrid.aspx。