为什么我在C#compact框架中“无法建立与网络的连接”?

时间:2014-11-18 10:59:07

标签: c# .net http

注意:以下用户名和密码是100%正确的...请帮帮我

public static bool DownloadFile(string url, string destination)
    {
        bool success = false;
        int i = 0;

        System.Net.HttpWebRequest request = null;
        System.Net.WebResponse response = null;
        Stream responseStream = null;
        FileStream fileStream = null;



        try
        {
            i = 1;
            request=(HttpWebRequest)WebRequest.Create("http://retfsoftware.com/SiddhPrj/TimeClock Biopad.exe/");

           //request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            request.Method = "GET";




            request.Timeout = 100000; // 100 seconds
            request.Credentials = new NetworkCredential("usernmae", "password");
            //request.Credentials = CredentialCache.DefaultCredentials;

            response = request.GetResponse();

            i=2;
            responseStream = response.GetResponseStream();

            fileStream = File.Open(destination, FileMode.Create, FileAccess.Write, FileShare.None);

            // read up to ten kilobytes at a time
            int maxRead = 10240;
            byte[] buffer = new byte[maxRead];
            int bytesRead = 0;
            int totalBytesRead = 0;

            // loop until no data is returned
            while ((bytesRead = responseStream.Read(buffer, 0, maxRead)) > 0)
            {
                totalBytesRead += bytesRead;
                fileStream.Write(buffer, 0, bytesRead);
            }

            // we got to this point with no exception. Ok.
            success = true;
        }
        catch (Exception exp)
        {
            // something went terribly wrong.
            success = false;
            MessageBox.Show(exp.Message + (i));
        }
        finally
        {
            // cleanup all potentially open streams.

            if (null != responseStream)
                responseStream.Close();
            if (null != response)
                response.Close();
            if (null != fileStream)
                fileStream.Close();
        }

        // if part of the file was written and the transfer failed, delete the partial file
        if (!success && File.Exists(destination))
            File.Delete(destination);

        return success;
    }

请找到上面的代码并帮助我

2 个答案:

答案 0 :(得分:0)

对于仍然存在此问题的任何人,我为我的案件找到了一些解决方案。

  • 如果使用仿真器:使用工具->设备仿真器管理器来建立与仿真器的网络连接。
  • 如果您使用的是实际的Windows移动设备:转到设备上的设置->连接应用程序,然后导航至高级并单击例外。在这里,我为运行移动.NET CF应用程序的REST服务的计算机/主机添加了ip。 Web请求不再引发异常。

答案 1 :(得分:-1)

您需要使用FtpWebRequest类型。在您的示例中,您使用的是HttpWebRequest,HTTP不是FTP服务器与其客户端通信的方式。这是一个不同的协议。