1

The idea is simple, i am creating a service where user can put the direct link of a file that is being hosted on another website and my program will open a stream to that remote server and start reading the file in bytes and then return each readed byte to the user.

Example : Internet download manager will go to my page, then my code will fetch the remote file and read it in bytes and return each byte to Internet download manager to download the file.

here is my code

    public void Index()
    {
        using (WebClient wcDownload = new WebClient())
        {
            try
            {
                // Create a request to the file we are downloading
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://FILE-IS-NOT-ON-MY-SERVER.com/file.zip");
                // Set default authentication for retrieving the file
                webRequest.Credentials = CredentialCache.DefaultCredentials;
                // Retrieve the response from the server
                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                // Ask the server for the file size and store it
                Int64 fileSize = webResponse.ContentLength;

                // Open the URL for download 
                Stream strResponse = wcDownload.OpenRead("http://FILE-IS-NOT-ON-MY-SERVER.com/file.zip");

                // It will store the current number of bytes we retrieved from the server
                int bytesSize = 0;
                // A buffer for storing and writing the data retrieved from the server
                byte[] downBuffer = new byte[500000000];


                // Loop through the buffer until the buffer is empty
                while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                {
                    // i want to return each byte to the user for example Internet Download Manager
                }


                // When the above code has ended, close the streams
                strResponse.Close();
            }
            catch (Exception)
            {

            }
        }
    }

i know it is messy but i really don't know how to return each byte to the user.

4

2 回答 2

1

我认为这个链接http://support.microsoft.com/kb/812406可以帮助你很多!您只需要更改打开的文件以供下载。

于 2013-03-24T10:26:02.733 回答
1

简而言之,您想从请求的响应中获取一个流,然后将该流分配给您的响应流(或写入您的响应流)。

我认为这个 SO question有一个很好的答案。

于 2013-03-25T05:04:36.073 回答