C# 直接下载文件到内存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19686599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:37:01  来源:igfitidea点击:

Download file directly to memory

c#winformsvisual-studio-2012farpoint-spread

提问by daved

I would like to load an excel file directly from an ftp site into a memory stream. Then I want to open the file in the FarPoint Spread control using the OpenExcel(Stream) method. My issue is I'm not sure if it's possible to download a file directly into memory. Anyone know if this is possible?

我想直接从 ftp 站点将 excel 文件加载到内存流中。然后我想使用 OpenExcel(Stream) 方法在 FarPoint Spread 控件中打开文件。我的问题是我不确定是否可以将文件直接下载到内存中。有谁知道这是否可能?

采纳答案by Attila

Yes, you can download a file from FTP to memory.

是的,您可以将文件从 FTP 下载到内存。

I think you can even pass the Stream from the FTP server to be processed by FarPoint.

我认为您甚至可以将来自 FTP 服务器的 Stream 传递给 FarPoint 进行处理。

WebRequest request = FtpWebRequest.Create("ftp://asd.com/file");

using (WebResponse response = request.GetResponse())
{
    Stream responseStream = response.GetResponseStream();
    OpenExcel(responseStream);
}

Using WebClient you can do nearly the same. Generally using WebClient is easier but gives you less configuration options and control (eg.: No timeout setting).

使用 WebClient 您可以做几乎相同的事情。通常使用 WebClient 更容易,但为您提供较少的配置选项和控制(例如:无超时设置)。

WebClient wc = new WebClient();
using (MemoryStream stream = new MemoryStream(wc.DownloadData("ftp://asd.com/file")))
{
    OpenExcel(stream);
}

回答by vivat pisces

Take a look at WebClient.DownloadData. You should be able to download the file directory to memory and not write it to a file first.

看看WebClient.DownloadData。您应该能够将文件目录下载到内存中,而不是先将其写入文件。

This is untested, but something like:

这是未经测试的,但类似于:

var spreadSheetStream
    = new MemoryStream(new WebClient().DownloadData(yourFilePath));

I'm not familiar with FarPoint though, to say whether or not the stream can be used directly with the OpenExcelmethod. Online examplesshow the method being used with a FileStream, but I'd assume any kind of Streamwould be accepted.

不过,我对 FarPoint 并不熟悉,要说流是否可以直接与该OpenExcel方法一起使用。在线示例显示了与 a 一起使用的方法FileStream,但我假设任何类型的Stream都将被接受。

回答by Er?in Dedeo?lu

Download file from URL to memory. My answer does not exactly show, how to download a file for use in Excel, but shows how to create a generic-purpose in-memory byte array.

从 URL 下载文件到内存。 我的回答并没有完全说明如何下载文件以在 Excel 中使用,而是说明了如何创建通用的内存中字节数组。

    private static byte[] DownloadFile(string url)
    {
        byte[] result = null;

        using (WebClient webClient = new WebClient())
        {
            result = webClient.DownloadData(url);
        }

        return result;
    }