c# 下载网络文件至本地

1.使用 DownloadFile 方式

WebClient wClient = new WebClient();
string  url= "https://ss3.bdstatic.com/lPoZeXSm1A5BphGlnYG/skin/34.jpg";
string filename =  System.IO.Path.GetFileName(url);
wClient.DownloadFile(url, AppDomain.CurrentDomain.BaseDirectory+ filename);

2.文件流读取方式

            WebClient wClient = new WebClient();
            string url = "https://ss3.bdstatic.com/lPoZeXSm1A5BphGlnYG/skin/34.jpg";
            string filename = Path.GetFileName(url);
            Stream str = wClient.OpenRead(url);
            StreamReader reader = new StreamReader(str);
            byte[] mbyte = new byte[1000000];
            int allmybyte = (int)mbyte.Length;
            int startmbyte = 0;
            while (allmybyte > 0)
            {
                int m = str.Read(mbyte, startmbyte, allmybyte);
                if (m == 0)
                    break;
                startmbyte += m;
                allmybyte -= m;
            }
            reader.Dispose();
            str.Dispose();

            string path = AppDomain.CurrentDomain.BaseDirectory + filename;
            FileStream fstr = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            fstr.Write(mbyte, 0, startmbyte);
            fstr.Flush();
            fstr.Close();

发表评论

您的电子邮箱地址不会被公开。