使用 silverlight 读取 JSON 文件
Read a JSON File using silverlight
我需要从本地文件夹中读取 JSON 文件。是否可以使用 WebClient?
这是我目前拥有的代码:
WebClient client = new WebClient();
client.Headers["Content-Type"] = "application/json";
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
string url = "file - Copy.json";
client.OpenReadAsync(new Uri(url, UriKind.Relative));
}
private void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
StreamReader reader = new StreamReader(e.Result);
string json = reader.ReadToEnd();
}
在执行时,它会抛出一个 TargetInvocationException
。
这是什么原因造成的,我该如何解决?
是的,这可以通过一些小的改变来完成:
public static void Main(string[] args)
{
WebClient client = new WebClient();
client.Headers["Content-Type"] = "application/json";
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
string url = @"C:\Users\YourNameHere\Documents\Visual Studio 2013\Projects\TestingApp\TestingApp\Copy.json";
client.OpenReadAsync(new Uri(url, UriKind.Absolute));
}
private static void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
StreamReader reader = new StreamReader(e.Result);
string json = reader.ReadToEnd();
}
基本上您需要拥有 .json 文件的完整路径并将 UriKind 更改为 Absolute。上面的例子工作正常。
祝你好运!
我需要从本地文件夹中读取 JSON 文件。是否可以使用 WebClient?
这是我目前拥有的代码:
WebClient client = new WebClient();
client.Headers["Content-Type"] = "application/json";
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
string url = "file - Copy.json";
client.OpenReadAsync(new Uri(url, UriKind.Relative));
}
private void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
StreamReader reader = new StreamReader(e.Result);
string json = reader.ReadToEnd();
}
在执行时,它会抛出一个 TargetInvocationException
。
这是什么原因造成的,我该如何解决?
是的,这可以通过一些小的改变来完成:
public static void Main(string[] args)
{
WebClient client = new WebClient();
client.Headers["Content-Type"] = "application/json";
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
string url = @"C:\Users\YourNameHere\Documents\Visual Studio 2013\Projects\TestingApp\TestingApp\Copy.json";
client.OpenReadAsync(new Uri(url, UriKind.Absolute));
}
private static void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
StreamReader reader = new StreamReader(e.Result);
string json = reader.ReadToEnd();
}
基本上您需要拥有 .json 文件的完整路径并将 UriKind 更改为 Absolute。上面的例子工作正常。
祝你好运!