将文件直接下载到内存

本文关键字:内存 下载 文件 | 更新日期: 2023-09-27 18:37:25

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

将文件直接下载到内存

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

我认为您甚至可以将Stream从FTP服务器传递到FarPoint处理。

WebRequest request = FtpWebRequest.Create("ftp://asd.com/file");
using (WebResponse response = request.GetResponse())
{
    Stream responseStream = response.GetResponseStream();
    OpenExcel(responseStream);
}

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

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

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

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

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

不过,我不熟悉FarPoint,无法说该流是否可以直接与OpenExcel方法一起使用。在线示例显示了该方法与FileStream一起使用,但我认为任何类型的Stream都会被接受。

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

    private static byte[] DownloadFile(string url)
    {
        byte[] result = null;
        using (WebClient webClient = new WebClient())
        {
            result = webClient.DownloadData(url);
        }
        return result;
    }