C#怎么保存网络上的文件

2019-01-02 20:42发布

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://files.cnblogs.com/files/shousiji/ProcTools.rar");
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream fileStream = response.GetResponseStream();
int fileContentLength = (int)response.ContentLength;
byte[] fileBytes = new byte[fileContentLength];
fileStream.Read(fileBytes, 0, fileContentLength);
using (FileStream stream = File.Create("c:/2.rar"))
{
stream.Write(fileBytes, 0, fileBytes.Length);
stream.Close();
}

代码保存的文件,大小是一样了,但打开是已损坏的。
不知道怎么做了,各位大神帮忙看看!

标签:
1条回答
萌妹纸的霸气范
2楼-- · 2019-01-02 21:41

试试下面的代码

using (var response = request.GetResponse() as HttpWebResponse)
{
    using (var responseStream = response.GetResponseStream())
    {
        using (var fs = new FileStream("c:/2.rar", FileMode.Create))
        {
            responseStream.CopyTo(fs);
        }
    }
}
查看更多
登录 后发表回答