0

我有一个 PHP 脚本,它将用户重定向到文件下载。在 Web 浏览器中查看此页面时,系统会自动提示我选择保存文件的位置,并在SaveFileDialog.

我希望使用用 C# 编写的应用程序下载此文件。如何检索 PHP 脚本响应中包含的文件的文件名和扩展名?

我认为必须读取 PHP 变量,但我还没有找到正确的方法来读取它。我存储文件名和扩展名的 PHP 变量分别是$file$ext

我在这里阅读了几个问题,但我很困惑。一些用户谈论WebClient,其他人谈论HttpWebRequest

你能指出我正确的方向吗?

4

1 回答 1

1

看看这里,这里描述了下载和保存文件的过程。

以下是从请求响应标头中获取文件名的方法:

String header = client.ResponseHeaders["content-disposition"];
String filename = new ContentDisposition(header).FileName;

还有一个注意事项:这里的客户端是 WebClient 组件。这里是如何使用 WebClient 下载:在此处输入链接描述

------完整的解决方案----------------------------

事实证明,您的服务器使用身份验证。这就是为什么为了下载文件,我们必须通过身份验证。所以,写下完整的细节。这是代码:

 private class CWebClient : WebClient
    {
        public CWebClient()
            : this(new CookieContainer())
        { }
        public CWebClient(CookieContainer c)
        {
            this.CookieContainer = c;
        }
        public CookieContainer CookieContainer { get; set; }

        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                (request as HttpWebRequest).CookieContainer = this.CookieContainer;
            }
            return request;
        }
    }
    static void Main(string[] args)
    {
        var client = new CWebClient();
        client.BaseAddress = @"http://forum.tractor-italia.net/";
        var loginData = new NameValueCollection();
        loginData.Add("username", "demodemo");
        loginData.Add("password", "demodemo");
        loginData.Add("login","Login");
        loginData.Add("redirect", "download/myfile.php?id=1622");
        client.UploadValues("ucp.php?mode=login", null, loginData);

        string remoteUri = "http://forum.tractor-italia.net/download/myfile.php?id=1622";
        client.OpenRead(remoteUri);
        string fileName = String.Empty;
        string contentDisposition = client.ResponseHeaders["content-disposition"];
        if (!string.IsNullOrEmpty(contentDisposition))
    {
        string lookFor = @"=";
        int index = contentDisposition.IndexOf(lookFor, 0);
        if (index >= 0)
            fileName = contentDisposition.Substring(index + lookFor.Length+7);
    }//attachment; filename*=UTF-8''JohnDeere6800.zip

       client.DownloadFile(remoteUri, fileName);


    }

在我的电脑上工作。

于 2012-07-21T18:27:22.720 回答