C# 在线文件下载
方法一和方法二都可以下载文件
/// <summary>
/// 文件下载
/// </summary>
/// <param name="url">URL地址</param>
/// <param name="name">文件名</param>
/// <param name="path">路径</param>
/// <returns>运行结果</returns>
public bool FileDownload(string url,string name,string path) {
bool value=false;
if (path==""||path==null) {
path="C:\\Users\\Administrator\\.XMusicPlayer\\Music";
}
if (!path.EndsWith("\\")) {
path+="\\";
}
string fullpath = path + name+url.Substring(url.LastIndexOf("."));
if (File.Exists(fullpath)) {
File.Delete(fullpath);
}
HttpWebRequest request = null;//HTTP请求
HttpWebResponse response = null; //HTTP响应
BufferedStream streamWrite = null; //缓冲流
FileStream file = null; //文件流
Stream stream = null; //流
try {
request=WebRequest.CreateHttp(url);//向指定的URL地址发送请求
response=(HttpWebResponse)request.GetResponse();//获取响应
long fileLength = response.ContentLength;//获取响应的长度
stream=request.GetRequestStream();//获取响应流
Byte[] bytes = new Byte[fileLength];//创建等长度的字节数组
stream.Read(bytes,0,bytes.Length);//将流读入到字节数组中
file=new FileStream(fullpath,FileMode.CreateNew);//建立要下载的文件
file.SetLength(fileLength);//设置文件的大小
streamWrite=new BufferedStream(file);//得到文件的写入流
streamWrite.Write(bytes,0,bytes.Length);//向文件中写入字节数组
System.Media.SystemSounds.Beep.Play();
value=true;
} catch (Exception e) {
value=false;
ErrorLog.WriteError(e.ToString(),3);
} finally {
if (response!=null) {
response.Close();
}
if (streamWrite!=null) {
streamWrite.Close();
}
if (stream!=null) {
stream.Close();
}
if (file!=null) {
file.Close();
}
}
return value;
}
/// <summary>
/// 文件下载
/// </summary>
/// <param name="url">URL地址</param>
/// <param name="name">文件名</param>
/// <param name="path">路径</param>
/// <returns>运行结果</returns>
public static bool FileDownloads(string url,string name,string path) {
bool value=false;
if (path==""||path==null) {
path="C:\\Users\\Administrator\\.XMusicPlayer\\Music";
}
if (!path.EndsWith("\\")) {
path+="\\";
}
string fullpath = path + name+url.Substring(url.LastIndexOf("."));
if (File.Exists(fullpath)) {
File.Delete(fullpath);
}
WebResponse response = null;
HttpWebRequest request=null;
BufferedStream write=null;
Stream read = null;
FileStream file=null;
try {
request=(HttpWebRequest)WebRequest.Create(url);
response=request.GetResponse();
read=response.GetResponseStream();
file=new FileStream(fullpath,FileMode.CreateNew);
file.SetLength(response.ContentLength);
byte[] bytes=new byte[response.ContentLength];
read.Read(bytes,0,bytes.Length);
write=new BufferedStream(file);
write.Write(bytes,0,bytes.Length);
write.Flush();
value=true;
System.Media.SystemSounds.Beep.Play();
} catch (Exception e) {
value=false;
} finally {
if (response!=null) {
response.Close();
}
if (write!=null) {
write.Close();
}
if (file!=null) {
file.Close();
}
if (read!=null) {
read.Close();
}
}
return value;
}