根据网络路径批量下载文件保存到本地

namespace DownloadUrlFile
{
    public static class FileUriHelper
    {
        /// 
        /// 下载文件
        /// 
        /// url路径,如:http://1.1.1.1/1.txt
        /// 保存文件全路径,如 G:\1.txt
        /// 
        public static void DownloadFile(string url, string saveFullPath)
        {
            WebRequest webRequest = null;
            WebResponse webResponse = null;
            Stream stream = null;
            FileStream fileStream = null;
            try
            {
                webRequest = WebRequest.Create(url);

                //webRequest.Credentials = CredentialCache.DefaultCredentials;
                //webRequest.UseDefaultCredentials = true;

                webResponse = webRequest.GetResponse();
                stream = webResponse.GetResponseStream();
                if (stream == null)
                {
                    throw new Exception("当前流为空!");
                }
                fileStream = System.IO.File.Create(saveFullPath);
                int b = stream.ReadByte();
                while (b != -1)
                {
                    fileStream.WriteByte((byte) b);
                    b = stream.ReadByte();
                }
                fileStream.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
                if (webResponse != null)
                {
                    webResponse.Close();
                }
            }
        }
    }
}

你可能感兴趣的:(C#Helper)