HttpWebRequest &&FileStream分块读取和写入文件&WebClient

来源:互联网 发布:淘宝包裹放微信二维码 编辑:程序博客网 时间:2024/05/28 11:30

//HttpWebRequest  下载文件

private void DownloadFile(string filePath)
          {
              string[] temp = filePath.Split(new string[] { @"/" }, StringSplitOptions.None);
              string fileName = temp[temp.Length - 1];
              string PhysicalFilePath = Request.PhysicalApplicationPath + ConfigurationManager.AppSettings["UploadFilePath"];
              if (!Directory.Exists(PhysicalFilePath))
                  Directory.CreateDirectory(PhysicalFilePath);
              if (!System.IO.File.Exists(PhysicalFilePath + "\\" + fileName))
              {
                  Uri downUri = new Uri(@"http://192.168.1.1" + filePath);

                  HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(downUri);

   //设置接收对象的范围为0-10000000字节。
                      hwr.AddRange(0, 10000000);
                  using (Stream stream = hwr.GetResponse().GetResponseStream())
                  {                   
                      //文件流,流信息读到文件流中,读完关闭
                      using (FileStream fs = System.IO.File.Create(PhysicalFilePath + "\\" + fileName))
                      {
                          //建立字节组,并设置它的大小是多少字节


                          byte[] bytes = new byte[10240];
                          int n = 1;
                          while (n > 0)
                          {
                              //一次从流中读多少字节,并把值赋给N,当读完后,N为0,并退出循环
                              n = stream.Read(bytes, 0, 10240);
                              fs.Write(bytes, 0, n); //将指定字节的流信息写入文件流中
                          }
                      }
                  }
              }
          }

static public void HttpRemoteDownload2()
        {
            string URLAddress = "http://192.168.1.106/ttIP.txt";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URLAddress);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            List<byte> btlst = new List<byte>();
            int b = responseStream.ReadByte();
            while (b > -1)
            {
                btlst.Add((byte)b);
                b = responseStream.ReadByte();
            }

            byte[] bts = btlst.ToArray();

            File.WriteAllBytes("testDownload.txt", bts); // 保存文件
        }

//FileStream分块读取和写入文件

 static void Main(string[] args)

        {

            FileStream fsOutput = new FileStream("D:\\wwwrite.txt", FileMode.Create | FileMode.Append);
            FileStream fs;
            //获得文件所在路径
            string filePath = "C:\\rrr.txt";

            //打开文件
            try
            {
                fs = new FileStream(filePath, FileMode.Open);
            }
            catch (Exception)
            {
                throw;
            }
            int chunkSize = 100;
            //尚未读取的文件内容长度
            long left = fs.Length;
            //存储读取结果
            byte[] bytes = new byte[chunkSize];
           
            //读取位置
            int start = 0;
            //实际返回结果长度
            int num = 0;
            //当文件未读取长度大于0时,不断进行读取
            while (left > 0)
            {
                fs.Position = start;
                num = 0;
                if (left < chunkSize)
                {
                    bytes = new byte[left];
                    num = fs.Read(bytes, 0, Convert.ToInt32(left));
                }
                else
                {
                    num = fs.Read(bytes, 0, chunkSize);
                }
                
               
                    //开始写入
                    fsOutput.Write(bytes, 0, bytes.Length);
                    //清空缓冲区
                    fsOutput.Flush();                 
                               
                Array.Clear(bytes, 0, bytes.Length);
                if (num == 0)
                    break;
                start += num;
                left -= num;
                Console.WriteLine(Encoding.UTF8.GetString(bytes));
            }
          
            Console.ReadLine();
            fs.Close();


            fsOutput.Close();

        }

//WebClient

static  public void HttpRemoteDownload()
        {
            string URLAddress = "http://192.168.1.106/ttIP.txt";
            WebClient client = new WebClient();
            Stream str = client.OpenRead(URLAddress);
            StreamReader reader = new StreamReader(str);
            byte[] fileData = new byte[1000000];
            int fileDataLength = (int)fileData.Length;
            int startIndex = 0;

            while (fileDataLength > 0)
            {

                int m = str.Read(fileData, startIndex, fileDataLength);
                if (m == 0)
                    break;


                startIndex += m;
                fileDataLength -= m;
            }

            reader.Dispose();
            str.Dispose();
            string receivePath = @"C:\";
            string path = receivePath + System.IO.Path.GetFileName(URLAddress);
            FileStream fstr = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            fstr.Write(fileData, 0, startIndex);
            fstr.Flush();
            fstr.Close();
        }

0 0
原创粉丝点击