通过HttpWebRequest C#将多个远程文件复制到另一个远程文件

copy multiple remote files to another remote file via HttpWebRequest C#

我有一个包含 n 个文件的远程文件夹,我需要将内容复制到另一个远程文件中。我想这可以通过流来完成,这是我尝试过的:

            WebRequest destRequest = WebRequest.Create(destFile);
            destRequest.Method = "PUT";
            destRequest.Headers.Add("x-ms-blob-type", "BlockBlob"); //just an example with Azure blob, doesn't matter


            using (Stream destStream = destRequest.GetRequestStream())
            {
                string sourceName = "mysourcefolder";

                int blockSize = 8388608; //all the files have the same lenght, except one (sometimes)
                for (int i = 0; i < n; i++)
                {
                    string source = sourceName + i;
                    WebRequest sourceRequest = WebRequest.Create(source);
                    destRequest.Method = "GET";
                    HttpWebResponse destResp = (HttpWebResponse)destRequest.GetResponse();
                    using (Stream sourceStream = destResp.GetResponseStream())
                    {
                        sourceStream.CopyTo(destStream, blockSize);
                    }
                }

                Console.Write("ok");
            }

        }
        catch (Exception e)
        {
            Console.Write("nope !");
        }

我的代码中存在多个问题:

1) 我必须在我的 PUT 请求中指定长度。可能是 blockSize*n 因为我对此没有例外;

2) 如果是这样,我还有例外Cannot close stream until all bytes are written。这是什么意思?

资源和目标请求存在混淆。 我已经在更改行中添加了注释。

        WebRequest destRequest = WebRequest.Create(destFile);
        destRequest.Method = "PUT";
        destRequest.Headers.Add("x-ms-blob-type", "BlockBlob"); //just an example with Azure blob, doesn't matter
        using (Stream destStream = destRequest.GetRequestStream())
        {
            string sourceName = "mysourcefolder";
            //int blockSize = 8388608; //all the files have the same lenght, except one (sometimes) //all the files have the same lenght, except one (sometimes)
            for (int i = 0; i < n; i++)
            {
                string source = sourceName + i;
                WebRequest sourceRequest = WebRequest.Create(source);
                destRequest.Method = "GET";

                //HttpWebResponse destResp = (HttpWebResponse)destRequest.GetResponse();
                //using (Stream sourceStream = destResp.GetResponseStream())

                // you need source response
                HttpWebResponse sourceResp = (HttpWebResponse)sourceRequest.GetResponse();
                using (Stream sourceStream = sourceResp.GetResponseStream())
                {
                    sourceStream.CopyTo(destStream);
                }
            }
            // The request is made here
            var destinationResponse = (HttpWebResponse) destRequest.GetResponse();
            //Console.Write("ok");
            Console.Write(destinationResponse.StatusCode.ToString());
        }