在 C# 中下载之前获取二进制文件的名称
首先让我描述一下情况。 我的 C# 应用程序向 PHP 服务器请求最新更新。它使用它的 URL 和一个简单的 POST 属性,例如:127.0.0.1/update.php?ver=0.2,如果没有版本低于 0.2,则服务器响应 404,如果有更新版本,则服务器响应 200 OK,并开始发送二进制文件在 mime 类型中:八位字节流。
我在获取此文件时没有任何问题,但在获取其文件名时遇到问题。
使用此代码:
WebClient webClient = new WebClient();
webClient.DownloadFile("http://127.0.0.1/update.php?ver=0.2", filename);
我必须输入我的文件名,但是如果我希望它与服务器上的文件具有相同的名称怎么办?下载之前如何获取它?
At first let me describe the situation.
My application in C# asks the PHP server for the newest update. It uses its URL and a simple POST attributes like: 127.0.0.1/update.php?ver=0.2, the server responds with 404 if there's no never version than 0.2 and with 200 OK when there's a newer version and starts sending the binary file in mime-type: octet-stream.
I don't have any problems with getting this file, but I'm having problems with getting its filename.
With this code:
WebClient webClient = new WebClient();
webClient.DownloadFile("http://127.0.0.1/update.php?ver=0.2", filename);
I have to put my filename but what if I want it to have THE SAME NAME as the file on server? How can I get it before downloading it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用
OpenRead()
那么您可以查看webClient.ResponseHeaders["content-disposition"]
是否有值并解析出 filename="blah.blah"部分。然而,网络上的绝大多数流没有文件名信息,当发送时,您可能需要根据内容类型重写文件扩展名,以便文件扩展名与所在计算机上的映射相匹配正在保存到。
If you use
OpenRead()
then you can see if there's a value forwebClient.ResponseHeaders["content-disposition"]
and parse out the filename="blah.blah" part.However the vast majority of streams on the web don't have filename information, and when it is sent you may want to re-write the file extension based on the content-type so that the file extension matches the mapping on the machine it is being save to.
这不可能直接实现,因为
WebClient
提供的高级功能不太适合此类场景。您可以采取多种方法,但它们都需要一种或另一种类型的更改。这里有几个:
DownloadString
),告诉您是否有更新及其名称,然后 调用DownloadFile
来获取更新本身,并知道名称。DownloadFile
的便利,在较低层处理HTTP请求;这样做,以便您能够读取 HTTP 响应标头,并添加一个标头(可以是任何内容,您甚至可以像X-Save-Filename:
一样编写一个标头)来告诉您什么文件名应该是.This is not directly possible because
WebClient
offers high-level functionality that doesn't lend itself too well to such scenarios.There are several approaches that you could take, but they all require changes of one type or other. Here are a couple:
DownloadString
) that tells you if there is an update and what its name is, then callDownloadFile
to get the update itself, knowing the name.DownloadFile
and handle the HTTP request at a lower level; do this so that you will be able to read the HTTP response headers, and add a header (can be anything, you can even make one up like e.g.X-Save-Filename:
) that tells you what the filename should be.