【问题标题】:Creating a file stream for a HTTP file为 HTTP 文件创建文件流
【发布时间】:2020-02-16 04:01:30
【问题描述】:

我需要使用 URL 直接在服务器位置创建文件流。类似的东西

fs = new FileStream("http://SiteName.in/abc/xyz/pqr.pdf", FileMode.Create);

但它给了我这个例外:

不支持 URI 格式

我尝试了许多其他选项,但没有提供令人满意的结果。

【问题讨论】:

  • 你想从流中读取还是写入流?
  • 考虑到 FileMode.Create,我认为他们想将文件上传到服务器
  • URL Formats are not supported 的可能重复项
  • 我需要直接在指定位置创建和写入。当我们使用 fs = new FileStream("c:\\pqr.pdf", FileMode.Create) 它可以工作,但不能通过提供 URL m 搜索正确的方式来工作..

标签: c# .net filestream


【解决方案1】:

您不能创建 HTTP 请求的 文件 流。这不是课堂和网络的运作方式。

改用WebClient.OpenWrite 或直接WebClient.UploadString

WebClient wc = new WebClient();
using (Stream s = wc.OpenWrite("url"))
{
    ...
}

当然,您的服务器应该支持 POST 请求。您也可以使用更手动的HttpWebRequest 类。

【讨论】:

  • 您可以使用请求|响应流。
  • @HenkHolterman:确实。或OpenWrite,如果出于性能原因需要Stream,它可能比UploadString 更好。
【解决方案2】:

您只需将文件下载到Stream

public static Stream DownloadFile(string TargetFile)
{
    WebClient MyWebClient = new WebClient();
    byte[] BytesFile = MyWebClient.DownloadData(TargetFile);

    MemoryStream iStream = new MemoryStream(BytesFile);

    return iStream;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多