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?

有帮助吗?

解决方案

If you use OpenRead() then you can see if there's a value for webClient.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.

其他提示

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:

  1. You can split the functionality into two parts: make one call (e.g. with DownloadString) that tells you if there is an update and what its name is, then call DownloadFile to get the update itself, knowing the name.
  2. Give up the convenience of 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.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top