Sheehan Alam
Sheehan Alam

Reputation: 60909

How can I convert a string to a stream?

I would like to parse some JSON:

void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(e.Result)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(STMsgObj));
            STMsgObj[] messages = (STMsgObj[])serializer.ReadObject(stream);

            foreach(STMsgObj aMsg in messages){
                MessageBox.Show(aMsg.body, "Data Passed", MessageBoxButton.OK); 
            }
        }
    }

How can I convert e.Result into a stream?

Exception:

System.InvalidCastException was unhandled
  Message=InvalidCastException
  StackTrace:
       at StockTwits.ViewModels.StreamPage.webClient_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
       at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
       at System.Net.WebClient.DownloadStringOperationCompleted(Object arg)
       at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
       at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
       at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
       at System.Delegate.DynamicInvokeOne(Object[] args)
       at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
       at System.Delegate.DynamicInvoke(Object[] args)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
       at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
       at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
       at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
       at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)

Upvotes: 1

Views: 2109

Answers (4)

SLaks
SLaks

Reputation: 887837

Your JSON data isn't an array.

Upvotes: 0

spender
spender

Reputation: 120498

Given that WebClient wraps an API that is already stream based means there are a number of unnecessary conversions. You might want to consider swapping your WebClient for plain old HttpWebRequest, which hands you a stream out of the box.

HttpWebRequest req=(HttpWebRequest)WebRequest.Create(myUrl);
using(var resp=req.GetResponse())
using(var stream=resp.GetResponseStream())
{
    ...
}

Upvotes: 0

SLaks
SLaks

Reputation: 887837

Call DownloadDataAsync instead.

You can then pass new MemoryStream(e.Result) from the DownloadDataCompleted event.

If you really want to stick with DownloadStringAsync, you can pass XmlReader.Create(new StringReader(e.Result)).

Upvotes: 0

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29642

Try the following:

using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(e.Result)))
{
    // Your code here, using stream.
}

Upvotes: 6

Related Questions