从绝对路径获取流? [英] Getting a Stream from an absolute path?

查看:42
本文介绍了从绝对路径获取流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个方法:

public RasImage Load(Stream stream);

如果我想加载一个网址:

if I want to load a url like:

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

如何将此 url 放入流中并将其传递到我的 load 方法中?

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

推荐答案

这是一种方法.我真的不知道这是否是最好的方法,但它确实有效.

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:看起来在 Silverlight 中,WebRequest 类没有 GetResponse 方法;您别无选择,只能异步执行此操作.


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();

这篇关于从绝对路径获取流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆