views:

44

answers:

2

Hi Guys,

I have this method:

public RasImage Load(Stream stream);

if I want to load a url like:

string _url = "http://localhost/Application1/Images/Icons/hand.jpg";

How can I make this url in to a stream and pass it into my load method?

+3  A: 

Here's one way. I don't really know if it's the best way or not, but it works.

// requires System.Net namespace
WebRequest request = WebRequest.Create(_url);

using (var response = request.GetRespone())
using (var stream = response.GetResponseStream())
{
    RasImage image = Load(stream);
}

UPDATE: It looks like in Silverlight, the WebRequest class has no GetResponse method; you've no choice but to do this asynchronously.

Below is some sample code illustrating how you might go about this. (I warn you: I wrote this just now, without putting much thought into how sensible it is. How you choose to implement this functionality would likely be quite different. Anyway, this should at least give you a general idea of what you need to do.)

WebRequest request = WebRequest.Create(_url);

IAsyncResult getResponseResult = request.BeginGetResponse(
    result =>
    {
        using (var response = request.EndGetResponse(result))
        using (var stream = response.GetResponseStream())
        {
            RasImage image = Load(stream);
            // Do something with image.
        }
    },
    null
);

Console.WriteLine("Waiting for response from '{0}'...", _url);
getResponseResult.AsyncWaitHandle.WaitOne();

Console.WriteLine("The stream has been loaded. Press Enter to quit.");
Console.ReadLine();
Dan Tao
A similar, but shorter approach would be to use `WebClient.OpenRead`.
Fredrik Mörk
@Fredrik: Nice, didn't know about that one. Goes to show there's almost always more than one way to skin a cat.
Dan Tao
Guys, these methods does not seem to be in the System.Net for the silverlight, any clues....`request.GetRespone())` or `WebClient.OpenRead` I can't use them
VoodooChild
+1  A: 

Dan's answer is a good one, though you're requesting from localhost. Is this a file you can access from the filesystem? If so, I think you should be able to just pass in a FileStream:

FileStream stream = new FileStream(@"\path\to\file", FileMode.Open);
Josh Wolf
It looks like the localhost path was just an example - he's likely to want to download images off the internet and manipulate them locally. Not that I would ever do such things >_>
JustLoren
Good catch on the localhost part; I hadn't even noticed.
Dan Tao
When I change it to a local fileSystem I am getting `File operation not permitted. Access to path '../images/Icons/thumb.gif' is denied.` on the FileStream...any clues
VoodooChild
Silverlight sandbox does not permit local file access... for ovbious reasons.
Denis