private static void RespCallback(IAsyncResult ar)
    {
        // State of request is asynchronous.
        RequestDeclare requestDeclare = (RequestDeclare)ar.AsyncState;

        FileWebRequest myFileWebRequest = requestDeclare.myFileWebRequest;

        // End the Asynchronus request by calling the 'EndGetResponse()' method.

        FileWebResponse myFileWebResponse = (FileWebResponse)myFileWebRequest.EndGetResponse(ar);

        // Reade the response into Stream.
        StreamReader streamReader = new StreamReader(myFileWebResponse.GetResponseStream());

        Char[] readBuffer = new Char[256];

        int count = streamReader.Read(readBuffer, 0, 256);

        Console.WriteLine("The contents of the file are :\n");

        while (count > 0)
        {
            String str = new String(readBuffer, 0, count);
            Console.WriteLine(str);
            count = streamReader.Read(readBuffer, 0, 256);
        }

        streamReader.Close();
        // Release the response object resources.
        myFileWebResponse.Close();
        allDone.Set();
        Console.WriteLine("File reading is over.");
    }
Ejemplo n.º 2
0
        public override Uri GetUserRequest(Uri input)
        {
            // Create a request for the local filepath (ex. C:/Users/joxx01812/source/repos/sqlFile.csv).
            FileWebRequest request = (FileWebRequest)FileWebRequest.Create(input);

            // Get the response.
            FileWebResponse response = (FileWebResponse)request.GetResponse();

            // Get the stream containing content returned by the server.
            // The using block ensures the stream is automatically closed.
            using (Stream dataStream = response.GetResponseStream())
            {
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);

                // Read the content.
                string responseFromUserInput = reader.ReadToEnd();

                // Display the content.
                Console.WriteLine(responseFromUserInput);

                // CleanUp streams.
                reader.Close();
                dataStream.Close();
            }
            // Close the response.
            response.Close();
            return(input);
        }
Ejemplo n.º 3
0
// <Snippet1>
    public static void GetPage(String url)
    {
        try
        {
            Uri fileUrl = new Uri("file://" + url);
            // Create a 'FileWebrequest' object with the specified Uri .
            FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create(fileUrl);
            // Send the 'fileWebRequest' and wait for response.
            FileWebResponse myFileWebResponse = (FileWebResponse)myFileWebRequest.GetResponse();
            // Display all Headers present in the response received from the Uri.
            Console.WriteLine("\r\nThe following headers were received in the response:");
            // Display each header and the key of the response object.
            for (int i = 0; i < myFileWebResponse.Headers.Count; ++i)
            {
                Console.WriteLine("\nHeader Name:{0}, Header value :{1}", myFileWebResponse.Headers.Keys[i],
                                  myFileWebResponse.Headers[i]);
            }
            myFileWebResponse.Close();
        }
        catch (WebException e)
        {
            Console.WriteLine("\r\nWebException thrown.The Reason for failure is : {0}", e.Status);
        }
        catch (Exception e)
        {
            Console.WriteLine("\nThe following Exception was raised : {0}", e.Message);
        }
    }
Ejemplo n.º 4
0
        public void GetResponse_File_Exists()
        {
            Stream s = File.Create(_tempFile);

            s.Close();
            FileWebRequest  req   = (FileWebRequest)WebRequest.Create(_tempFileUri);
            FileWebResponse respA = null;
            FileWebResponse respB = null;

            try {
                respA = req.GetResponse() as FileWebResponse;
                Assert.IsNotNull(respA, "#1");
                respB = req.GetResponse() as FileWebResponse;
                Assert.IsNotNull(respB, "#2");
                Assert.AreSame(respA, respB, "#3");
            } finally {
                if (respA != null)
                {
                    respA.Close();
                }
                if (respB != null)
                {
                    respB.Close();
                }
            }
        }
Ejemplo n.º 5
0
// <Snippet1>
    public static void GetPage(String url)
    {
        try
        {
            Uri fileUrl = new Uri("file://" + url);

            // Create a 'FileWebrequest' object with the specified Uri .
            FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create(fileUrl);

            // Send the 'fileWebRequest' and wait for response.
            FileWebResponse myFileWebResponse = (FileWebResponse)myFileWebRequest.GetResponse();

            Console.WriteLine("\nThe Uri of the file system resource that provided the response is :\n{0}\n\n", myFileWebResponse.ResponseUri);

            // Release resources of response object.
            myFileWebResponse.Close();
        }
        catch (WebException e)
        {
            Console.WriteLine("\r\nWebException thrown.The Reason for failure is : {0}", e.Status);
        }
        catch (Exception e)
        {
            Console.WriteLine("\nThe following Exception was raised : {0}", e.Message);
        }
    }
Ejemplo n.º 6
0
        private XmlDocument getUpdateFile(string updateUrl)
        {
            XmlDocument Winkle_XMLdoc = null;

            if (updateUrl.StartsWith("file", true, System.Globalization.CultureInfo.CurrentCulture))
            {
                FileWebRequest  Winkle_Request;
                FileWebResponse Winkle_Response = null;

                try
                {
                    Winkle_Request = (FileWebRequest)WebRequest.Create(string.Format(updateUrl));
                    //Winkle_Request.UserAgent = @"Winkle automatic update system " + winkleVersion;
                    Winkle_Response = (FileWebResponse)Winkle_Request.GetResponse();
                    Winkle_XMLdoc   = new XmlDocument();
                    Winkle_XMLdoc.Load(Winkle_Response.GetResponseStream());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                if (Winkle_Response != null)
                {
                    Winkle_Response.Close();
                }
            }
            else
            {
                HttpWebRequest  Winkle_Request;
                HttpWebResponse Winkle_Response = null;

                try
                {
                    Winkle_Request           = (HttpWebRequest)WebRequest.Create(string.Format(updateUrl));
                    Winkle_Request.UserAgent = @"Winkle automatic update system " + winkleVersion;
                    Winkle_Response          = (HttpWebResponse)Winkle_Request.GetResponse();
                    Winkle_XMLdoc            = new XmlDocument();
                    Winkle_XMLdoc.Load(Winkle_Response.GetResponseStream());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                if (Winkle_Response != null)
                {
                    Winkle_Response.Close();
                }
            }

            return(Winkle_XMLdoc);
        }
Ejemplo n.º 7
0
        private bool UrlCheck(string strUrl)
        {
            HttpWebRequest  webRequest;
            HttpWebResponse webResponse = null;
            FileWebRequest  fileRequest;
            FileWebResponse fileResponse = null;
            bool            isFile       = false;

            try
            {
                isFile = (HttpWebRequest.Create(strUrl) is FileWebRequest);

                if (isFile)
                {
                    fileRequest  = (FileWebRequest)FileWebRequest.Create(strUrl);
                    fileResponse = (FileWebResponse)fileRequest.GetResponse();
                    if (fileResponse == null)
                    {
                        return(false);
                    }
                    return(true);
                }
                else
                {
                    webRequest  = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                    webResponse = (HttpWebResponse)webRequest.GetResponse();
                    if (webResponse == null)
                    {
                        return(false);
                    }
                    return(webResponse.StatusCode == HttpStatusCode.OK);
                }
            }
            catch
            {
                if (fileResponse != null)
                {
                    fileResponse.Close();
                }

                if (webResponse != null)
                {
                    webResponse.Close();
                }

                return(false);
            }
        }
    public static void GetPage(String url)
    {
        try
        {
// <Snippet1>
            Uri fileUrl = new Uri("file://" + url);
            // Create a 'FileWebrequest' object with the specified Uri.
            FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create(fileUrl);
            // Send the 'FileWebRequest' object and wait for response.
            FileWebResponse myFileWebResponse = (FileWebResponse)myFileWebRequest.GetResponse();

            // Get the stream object associated with the response object.
            Stream receiveStream = myFileWebResponse.GetResponseStream();

            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            // Pipe the stream to a higher level stream reader with the required encoding format.
            StreamReader readStream = new StreamReader(receiveStream, encode);
            Console.WriteLine("\r\nResponse stream received");

            Char[] read = new Char[256];
            // Read 256 characters at a time.
            int count = readStream.Read(read, 0, 256);
            Console.WriteLine("File Data...\r\n");
            while (count > 0)
            {
                // Dump the 256 characters on a string and display the string onto the console.
                String str = new String(read, 0, count);
                Console.Write(str);
                count = readStream.Read(read, 0, 256);
            }
            Console.WriteLine("");
            // Release resources of stream object.
            readStream.Close();
            // Release resources of response object.
            myFileWebResponse.Close();
// </Snippet1>
        }
        catch (WebException e)
        {
            Console.WriteLine("\r\nWebException thrown. The Reason for failure is : {0}", e.Status);
        }
        catch (Exception e)
        {
            Console.WriteLine("\nThe following Exception was raised : {0}", e.Message);
        }
    }
Ejemplo n.º 9
0
        private static void readFile()
        {
            try
            {
                // Create the file stream.
                Stream receiveStream = myFileWebResponse.GetResponseStream();

                // Create a reader object to read the file content.
                StreamReader readStream = new StreamReader(receiveStream);

                // Create a local buffer for a temporary storage of the
                // read data.
                char[] readBuffer = new Char[256];

                // Read the first 256 bytes.
                int count = readStream.Read(readBuffer, 0, 256);

                Console.WriteLine("The file content is:");
                Console.WriteLine("");

                // Loop to read the remaining data in blocks of 256 bytes
                // and display the data on the console.
                while (count > 0)
                {
                    String str = new String(readBuffer, 0, count);
                    Console.WriteLine(str + "\n");
                    count = readStream.Read(readBuffer, 0, 256);
                }

                readStream.Close();

                // Release the response object resources.
                myFileWebResponse.Close();
            }
            catch (WebException e)
            {
                Console.WriteLine("The WebException: " + e.Message);
            }
            catch (UriFormatException e)
            {
                Console.WriteLine("The UriFormatException: " + e.Message);
            }
        }
Ejemplo n.º 10
0
        private string MakeFileRequest(string Url)
        {
            Uri    uri     = new Uri(Url);
            string Content = string.Empty;

            if (uri.Scheme == Uri.UriSchemeFile)
            {
                FileWebRequest req = (FileWebRequest)FileWebRequest.Create(uri);

                FileWebResponse resp = req.GetResponse() as FileWebResponse;

                Stream stream = resp.GetResponseStream();

                using (StreamReader reader = new StreamReader(stream))
                {
                    Content = reader.ReadToEnd();
                }

                resp.Close();
            }

            return(Content);
        }
Ejemplo n.º 11
0
// <Snippet1>
// <Snippet2>
    public static void GetPage(String url)
    {
        try
        {
            Uri fileUrl = new Uri("file://" + url);
            // Create a 'FileWebrequest' object with the specified Uri.
            FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create(fileUrl);
            // Send the 'fileWebRequest' and wait for response.
            FileWebResponse myFileWebResponse = (FileWebResponse)myFileWebRequest.GetResponse();
            // Print the ContentLength and ContentType properties received as headers in the response object.
            Console.WriteLine("\nContent length :{0}, Content Type : {1}", myFileWebResponse.ContentLength, myFileWebResponse.ContentType);
            // Release resources of response object.
            myFileWebResponse.Close();
        }
        catch (WebException e)
        {
            Console.WriteLine("\r\nWebException thrown. The Reason for failure is : {0}", e.Status);
        }
        catch (Exception e)
        {
            Console.WriteLine("\nThe following Exception was raised : {0}", e.Message);
        }
    }
Ejemplo n.º 12
0
// <Snippet1>
    public static void GetPage(String url)
    {
        try
        {
            Uri fileUrl = new Uri("file://" + url);
            // Create a FileWebrequest with the specified Uri.
            FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create(fileUrl);
            // Send the 'fileWebRequest' and wait for response.
            FileWebResponse myFileWebResponse = (FileWebResponse)myFileWebRequest.GetResponse();
            // Process the response here.
            Console.WriteLine("\nResponse Received.Trying to Close the response stream..");
            // Release resources of response object.
            myFileWebResponse.Close();
            Console.WriteLine("\nResponse Stream successfully closed.");
        }
        catch (WebException e)
        {
            Console.WriteLine("\r\nWebException thrown. The Reason for failure is : {0}", e.Status);
        }
        catch (Exception e)
        {
            Console.WriteLine("\nThe following Exception was raised : {0}", e.Message);
        }
    }
Ejemplo n.º 13
0
        /// <summary>
        /// Can be called syncronized to get a Http Web ResponseStream.
        /// </summary>
        /// <param name="method">The HTTP request method</param>
        /// <param name="address">Url to request</param>
        /// <param name="newAddress">out string. return a new url, if the original requested is permanent moved</param>
        /// <param name="credentials">Url credentials</param>
        /// <param name="userAgent"></param>
        /// <param name="proxy">Proxy to use</param>
        /// <param name="ifModifiedSince">Header date</param>
        /// <param name="eTag">Header tag</param>
        /// <param name="timeout">Request timeout. E.g. 60 * 1000, means one minute timeout.
        /// If zero or less than zero, the default timeout of one minute will be used</param>
        /// <param name="responseResult">out. Result of the request</param>
        /// <param name="cookie">The cookie associated with the request</param>
        /// <param name="body">The body of the HTTP request (if it is a POST)</param>
        /// <param name="additonalHeaders">These are additional headers that are being specified to the Web request</param>
        /// <returns>Stream</returns>
        public static Stream GetResponseStream(HttpMethod method, string address, out string newAddress,
                                               ICredentials credentials,
                                               string userAgent,
                                               IWebProxy proxy, ref DateTime ifModifiedSince, ref string eTag,
                                               int timeout, out RequestResult responseResult, Cookie cookie, string body,
                                               WebHeaderCollection additonalHeaders)
        {
            bool      useDefaultCred    = false;
            int       requestRetryCount = 0;
            const int MaxRetries        = 25;

            newAddress = null;

send_request:

            string requestUri = address;

            if (useDefaultCred)
            {
                credentials = CredentialCache.DefaultCredentials;
            }

            WebResponse wr =
                GetResponse(method, address, credentials, userAgent, proxy, ifModifiedSince, eTag, timeout, cookie, body,
                            additonalHeaders);

            HttpWebResponse response     = wr as HttpWebResponse;
            FileWebResponse fileresponse = wr as FileWebResponse;

            if (response != null)
            {
                if (HttpStatusCode.OK == response.StatusCode ||
                    HttpExtendedStatusCode.IMUsed == (HttpExtendedStatusCode)response.StatusCode)
                {
                    responseResult = RequestResult.OK;
                    // stream will be disposed on response.Close():
                    Stream ret = MakeSeekableStream(response.GetResponseStream()); //GetDeflatedResponse(response);
                    response.Close();
                    return(ret);
                }
                if ((response.StatusCode == HttpStatusCode.MovedPermanently) ||
                    (response.StatusCode == HttpStatusCode.Moved))
                {
                    newAddress = HtmlHelper.ConvertToAbsoluteUrl(response.Headers["Location"], address, false);
                    address    = newAddress;
                    response.Close();

                    if (requestRetryCount < MaxRetries)
                    {
                        requestRetryCount++;
                        goto send_request;
                    }
                }
                else if (IsUnauthorized(response.StatusCode))
                {
                    //try with default credentials

                    useDefaultCred = true;
                    response.Close();

                    if (requestRetryCount < MaxRetries)
                    {
                        requestRetryCount++;
                        goto send_request;
                    }
                }
                else if (IsRedirect(response.StatusCode))
                {
                    address = HtmlHelper.ConvertToAbsoluteUrl(response.Headers["Location"], address, false);
                    response.Close();

                    if (requestRetryCount < MaxRetries)
                    {
                        requestRetryCount++;
                        goto send_request;
                    }
                }
                else if (IsAccessForbidden(response.StatusCode) &&
                         requestUri.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    throw new ClientCertificateRequiredException();
                }
                else if (response.StatusCode == HttpStatusCode.Gone)
                {
                    throw new ResourceGoneException();
                }
                else
                {
                    string statusCode = response.StatusDescription;
                    if (String.IsNullOrEmpty(statusCode))
                    {
                        statusCode = response.StatusCode.ToString();
                    }
                    response.Close();
                    throw new WebException(String.Format("Request of '{0}' gets unexpected HTTP response: {1}",
                                                         requestUri, statusCode));
                }

                // unauthorized more than MaxRetries
                if (IsUnauthorized(response.StatusCode))
                {
                    response.Close();
                    throw new ResourceAuthorizationException();
                }

                //we got a moved, redirect more than MaxRetries
                string returnCode = response.StatusDescription;
                if (String.IsNullOrEmpty(returnCode))
                {
                    returnCode = response.StatusCode.ToString();
                }
                response.Close();
                throw new WebException(String.Format("Request of '{0}' gets repeated HTTP response: {1}", requestUri,
                                                     returnCode));
            }

            if (fileresponse != null)
            {
                responseResult = RequestResult.OK;
                // stream will be disposed on response.Close():
                Stream ret = MakeSeekableStream(fileresponse.GetResponseStream()); //GetDeflatedResponse(fileresponse);
                fileresponse.Close();
                return(ret);
            }
            throw new ApplicationException("no handler for WebResponse. Address: " + requestUri);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="strUrl"></param>
        private void DownloadFile(string FileName, string strUrl)
        {
            HttpWebRequest  webRequest;
            HttpWebResponse webResponse = null;
            FileWebRequest  fileRequest;
            FileWebResponse fileResponse = null;
            bool            isFile       = false;

            try
            {
                System.Globalization.DateTimeFormatInfo dfi = null;
                System.Globalization.CultureInfo        ci  = null;
                ci  = new System.Globalization.CultureInfo("zh-CN");
                dfi = new System.Globalization.DateTimeFormatInfo();

                //WebRequest wr = WebRequest.Create("");

                //System.Net.WebResponse w=wr.
                DateTime      fileDate;
                long          totalBytes;
                DirectoryInfo theFolder = new DirectoryInfo(strTemp);
                string        fileName  = theFolder + FileName;
                if (strUrl.EndsWith(".exe"))
                {
                    strUrl = strUrl.Replace(".exe", ".dll");
                }
                isFile = (HttpWebRequest.Create(strUrl) is FileWebRequest);

                if (isFile)
                {
                    fileRequest  = (FileWebRequest)FileWebRequest.Create(strUrl);
                    fileResponse = (FileWebResponse)fileRequest.GetResponse();
                    if (fileResponse == null)
                    {
                        return;
                    }
                    fileDate   = DateTime.Now;
                    totalBytes = fileResponse.ContentLength;
                }
                else
                {
                    webRequest  = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                    webResponse = (HttpWebResponse)webRequest.GetResponse();
                    if (webResponse == null)
                    {
                        return;
                    }
                    fileDate   = webResponse.LastModified;
                    totalBytes = webResponse.ContentLength;
                }

                pbUpdate.Maximum = Convert.ToInt32(totalBytes);

                Stream stream;
                if (isFile)
                {
                    stream = fileResponse.GetResponseStream();
                }
                else
                {
                    stream = webResponse.GetResponseStream();
                }
                FileStream sw = new FileStream(fileName, FileMode.Create);
                int        totalDownloadedByte = 0;
                Byte[]     @by   = new byte[1024];
                int        osize = stream.Read(@by, 0, @by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    Application.DoEvents();
                    sw.Write(@by, 0, osize);
                    pbUpdate.Value = totalDownloadedByte;
                    osize          = stream.Read(@by, 0, @by.Length);
                }
                sw.Close();
                stream.Close();

                //System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName(AppName);

                ////关闭原有应用程序的所有进程
                //foreach (System.Diagnostics.Process pro in proc)
                //{
                //    pro.Kill();
                //}


                //DirectoryInfo theFolder = new DirectoryInfo(Path.GetTempPath() + "ysy");
                if (theFolder.Exists)
                {
                    foreach (FileInfo theFile in theFolder.GetFiles())
                    {
                        if (theFile.Name != UpdExeName + ".exe" && theFile.Name != UpdExeName + ".pdb" && theFile.Name != "Config.xml")
                        {
                            //如果临时文件夹下存在与应用程序所在目录下的文件同名的文件,则删除应用程序目录下的文件
                            if (File.Exists(this.m_workPath + "\\" + Path.GetFileName(theFile.FullName)))
                            {
                                File.Delete(this.m_workPath + "\\" + Path.GetFileName(theFile.FullName));
                                //将临时文件夹的文件移到应用程序所在的目录下
                                File.Move(theFile.FullName, this.m_workPath + "\\" + Path.GetFileName(theFile.FullName));
                            }
                        }
                    }
                }
                File.SetLastWriteTime(FileName, fileDate);
            }
            catch (Exception ex)
            {
                if (fileResponse != null)
                {
                    fileResponse.Close();
                }

                if (webResponse != null)
                {
                    webResponse.Close();
                }

                // MessageBox.Show(ex.Message);
                lblStatus.Text = "更新出错!" + ex.Message;
                lblStatus.Refresh();
            }
        }
        public void GetResponseStream()
        {
            FileWebRequest req = (FileWebRequest)WebRequest.Create(_tempFileUri);

            req.Method      = "PUT";
            req.ContentType = "image/png";
            using (Stream s = req.GetRequestStream()) {
                s.WriteByte(72);
                s.WriteByte(110);
                s.WriteByte(80);
                s.Flush();
            }
            req = (FileWebRequest)WebRequest.Create(_tempFileUri);
            FileWebResponse respA = null;
            FileWebResponse respB = null;
            FileStream      fsA   = null;
            FileStream      fsB   = null;

            try {
                respA = (FileWebResponse)req.GetResponse();
                fsA   = respA.GetResponseStream() as FileStream;
                Assert.IsNotNull(fsA, "#A1");
                Assert.IsTrue(fsA.CanRead, "#A2");
                Assert.IsTrue(fsA.CanSeek, "#A3");
                Assert.IsFalse(fsA.CanTimeout, "#A4");
                Assert.IsFalse(fsA.CanWrite, "#A5");
                Assert.AreEqual(3, fsA.Length, "#A6");
                Assert.AreEqual(0, fsA.Position, "#A7");
                try {
                    int i = fsA.ReadTimeout;
                    Assert.Fail("#A8:" + i);
                } catch (InvalidOperationException) {
                }
                try {
                    int i = fsA.WriteTimeout;
                    Assert.Fail("#A9:" + i);
                } catch (InvalidOperationException) {
                }

                respB = (FileWebResponse)req.GetResponse();
                fsB   = respB.GetResponseStream() as FileStream;
                Assert.IsNotNull(fsB, "#B1");
                Assert.IsTrue(fsB.CanRead, "#B2");
                Assert.IsTrue(fsB.CanSeek, "#B3");
                Assert.IsFalse(fsB.CanTimeout, "#B4");
                Assert.IsFalse(fsB.CanWrite, "#B5");
                Assert.AreEqual(3, fsB.Length, "#B6");
                Assert.AreEqual(0, fsB.Position, "#B7");
                try {
                    int i = fsB.ReadTimeout;
                    Assert.Fail("#B8:" + i);
                } catch (InvalidOperationException) {
                }
                try {
                    int i = fsB.WriteTimeout;
                    Assert.Fail("#B9:" + i);
                } catch (InvalidOperationException) {
                }
            } finally {
                if (respA != null)
                {
                    respA.Close();
                }
                if (respB != null)
                {
                    respB.Close();
                }
            }
        }
        private void SingleDownload(string fileInfo)
        {
            string strFilePath = string.Empty;
            string strDocName;

            try
            {
                strFilePath = fileInfo.Split('|')[0];
                strDocName  = fileInfo.Split('|')[1];

                strFilePath = HttpContext.Current.Server.MapPath(strFilePath);
                if (!File.Exists(strFilePath))
                {
                    HttpContext.Current.Response.Status = "404 Not Found";
                    HttpContext.Current.Response.Write("<script>alert('物理文件不存在,请联系管理员!');window.close();</script>");
                    return;
                }
                //取实际文档扩展名
                string strExtension = Path.GetExtension(strFilePath).ToLower();
                if (strExtension.StartsWith("."))
                {
                    strExtension = strExtension.Substring(1);
                }


                //网页文件类型时,设置text/html为响应头内容类型
                if (strExtension == "htm" || strExtension == "html" || strExtension == "mht")
                {
                    HttpContext.Current.Response.ContentType = "text/html";
                }
                else
                {
                    HttpContext.Current.Response.ContentType = "application/octet-stream";
                }

                //指定作为附件下载,不在 IE 中直接打开
                HttpContext.Current.Response.AddHeader("Content-Disposition", "filename = \"" + this.GetEscapeDocName(strDocName, 113) + "\";");

                //获取web.config中配置的分段下载下限
                string splitDownloadSizeConfig = System.Configuration.ConfigurationManager.AppSettings["SplitDownloadSize"];
                long   splitDownloadSize       = string.IsNullOrEmpty(splitDownloadSizeConfig) ? 40960 * 1024 : Convert.ToInt32(splitDownloadSizeConfig) * 1024;
                //获取文件实际大小
                long            fileSize = 0;
                FileWebResponse response = null;
                try
                {
                    response = (FileWebResponse)HttpWebRequest.Create(strFilePath).GetResponse();
                    fileSize = response.ContentLength;
                }
                catch (System.Exception ex)
                {
                    HttpContext.Current.Response.Write("下载过程中发生异常:" + ex.Message);
                }
                finally
                {
                    if (response != null)
                    {
                        response.Close();
                    }
                }
                //文件实际大小小于分段下载下限直接下载
                if (fileSize < splitDownloadSize)
                {
                    HttpContext.Current.Response.WriteFile(strFilePath);
                    //HttpContext.Current.Response.End();
                    //文件实际大小大于等于分段下载下限分段下载
                }
                else
                {
                    Stream stream = null;
                    byte[] buffer = new Byte[10000];
                    int    length;
                    long   dataToRead;
                    //Dim fileName As String = Path.GetFileName(strFilePath)
                    try
                    {
                        stream     = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                        dataToRead = stream.Length;
                        while (dataToRead > 0)
                        {
                            if (HttpContext.Current.Response.IsClientConnected)
                            {
                                //分段下载
                                length = stream.Read(buffer, 0, 10000);
                                HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                                HttpContext.Current.Response.Flush();
                                buffer     = new Byte[10000];
                                dataToRead = dataToRead - length;
                            }
                            else
                            {
                                //客户端在没有下载完前,关闭连接,直接设置为-1,避免死循环
                                dataToRead = -1;
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        HttpContext.Current.Response.Write("下载过程中发生异常:" + ex.Message);
                    }
                    finally
                    {
                        if (stream != null)
                        {
                            stream.Close();
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                HttpContext.Current.Response.Write("下载过程中发生异常:" + ex.Message);
                HttpContext.Current.Response.End();
            }
        }
Ejemplo n.º 17
0
        private void DownloadFile(string FileName, string strUrl)
        {
            HttpWebRequest  webRequest;
            HttpWebResponse webResponse = null;
            FileWebRequest  fileRequest;
            FileWebResponse fileResponse = null;
            bool            isFile       = false;

            try
            {
                System.Globalization.DateTimeFormatInfo dfi = null;
                System.Globalization.CultureInfo        ci  = null;
                ci  = new System.Globalization.CultureInfo("zh-CN");
                dfi = new System.Globalization.DateTimeFormatInfo();

                //WebRequest wr = WebRequest.Create("");

                //System.Net.WebResponse w=wr.
                DateTime      fileDate;
                long          totalBytes;
                DirectoryInfo theFolder = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
                string        fileName  = Path.Combine(theFolder.FullName, FileName);

                isFile = (HttpWebRequest.Create(strUrl) is FileWebRequest);

                if (isFile)
                {
                    fileRequest  = (FileWebRequest)FileWebRequest.Create(strUrl);
                    fileResponse = (FileWebResponse)fileRequest.GetResponse();
                    if (fileResponse == null)
                    {
                        return;
                    }
                    fileDate   = DateTime.Now;
                    totalBytes = fileResponse.ContentLength;
                }
                else
                {
                    webRequest  = (HttpWebRequest)HttpWebRequest.Create(strUrl);
                    webResponse = (HttpWebResponse)webRequest.GetResponse();
                    if (webResponse == null)
                    {
                        return;
                    }
                    fileDate   = webResponse.LastModified;
                    totalBytes = webResponse.ContentLength;
                }

                //pbUpdate.Maximum = Convert.ToInt32(totalBytes);

                Stream stream;
                if (isFile)
                {
                    stream = fileResponse.GetResponseStream();
                }
                else
                {
                    stream = webResponse.GetResponseStream();
                }
                FileStream sw = new FileStream(fileName, FileMode.Create);
                int        totalDownloadedByte = 0;
                Byte[]     @by   = new byte[1024];
                int        osize = stream.Read(@by, 0, @by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    sw.Write(@by, 0, osize);
                    //pbUpdate.Value = totalDownloadedByte;
                    osize = stream.Read(@by, 0, @by.Length);
                }
                sw.Close();
                stream.Close();

                File.SetLastWriteTime(FileName, fileDate);
            }
            catch //(Exception ex)
            {
                if (fileResponse != null)
                {
                    fileResponse.Close();
                }

                if (webResponse != null)
                {
                    webResponse.Close();
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Process the request (once). Get the response (page content, cookies, ...).
        /// </summary>
        private void ProcessRequest()
        {
            if (RequestProcessed)
            {
                return; // test, unlocked
            }
            lock (this)
            {
                if (RequestProcessed)
                {
                    return;                   // double checked lock, test again
                }
                RequestProcessed = true;

                StorageValue data = (StorageValue)DataCache.GetItem(StorageKey,
                                                                    delegate(out DateTime expiration)
                {
                    WebRequest webreq = WebRequest.Create(ContextUri);

                    string RespContent           = null;
                    CookieCollection RespCookies = null;

                    if (webreq is HttpWebRequest)
                    {
                        HttpWebRequest req = (HttpWebRequest)webreq;

                        req.Referer           = (RefererContext != null && RefererContext.ContextUri != null) ? RefererContext.ContextUri.AbsoluteUri : null;
                        req.UserAgent         = DefaultUserAgent;
                        req.Timeout           = 30000;
                        req.AllowAutoRedirect = false;
                        req.KeepAlive         = false;
                        var cookieJar         = req.CookieContainer = new CookieContainer();
                        if (RefererContext != null && RefererContext.Cookies != null)
                        {       // TODO: filter cookies by domain and path
                            req.CookieContainer.Add(RefererContext.Cookies);
                        }
                        //req.Headers.Add("Accept-Language", "en,cs");

                        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

                        // page content
                        Stream RespStream = resp.GetResponseStream();
                        RespContent       = new StreamReader(RespStream /*, Encoding.GetEncoding(resp.ContentEncoding)*/).ReadToEnd();
                        RespStream.Close();

                        // cookies
                        foreach (Cookie c in cookieJar.GetCookies(req.RequestUri))
                        {
                            if (RespCookies == null)
                            {
                                RespCookies = new CookieCollection();
                            }

                            RespCookies.Add(c);
                        }

                        // TODO: headers (language, cache expire, content type, encoding, Response URI, ...)

                        // close the response
                        resp.Close();
                    }
                    else if (webreq is FileWebRequest)
                    {
                        FileWebRequest req   = (FileWebRequest)webreq;
                        FileWebResponse resp = (FileWebResponse)req.GetResponse();

                        // page content
                        Stream RespStream = resp.GetResponseStream();
                        RespContent       = new StreamReader(RespStream /*, Encoding.GetEncoding(resp.ContentEncoding)*/).ReadToEnd();
                        RespStream.Close();

                        // close the response
                        resp.Close();
                    }

                    expiration = DateTime.Now.AddHours(1.0);        // TODO: time based on HTML header or HtmlContext parameters

                    return(new StorageValue()
                    {
                        Content = RespContent, Cookies = RespCookies
                    });
                }
                                                                    );

                _Content = data.Content;
                _Cookies = data.Cookies;
            }
        }
Ejemplo n.º 19
0
 public override void Close()
 {
     _webResponse.Close();
 }