通过http下载音频并存储在c#中的本地文件夹中

时间:2014-06-06 02:18:03

标签: c# http audio

任何人都可以在c#中与我分享一段代码,我可以使用http请求下载.wmv格式的音频文件并存储在本地文件夹中吗?

1 个答案:

答案 0 :(得分:1)

您可以使用网络客户端。

using System.Net;

WebClient webClient = new WebClient();
webClient.DownloadFile("http://example.com/myfile.wmv", @"c:\myfile.wmv");

使用http网络请求

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com/myfile.wmv");
request.Method = WebRequestMethods.Http.Get;
request.ContentType = "video/x-ms-wmv"; 
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream reader = response.GetResponseStream();

byte[] inBuf = new byte[response.ContentLength];
int bytesToRead = (int)inBuf.Length;
int bytesRead = 0;
while (bytesToRead > 0)
{
    int n = reader.Read(inBuf, bytesRead, bytesToRead);
    if (n == 0)
    break;
    bytesRead += n;
    bytesToRead -= n;
}
FileStream fstr = new FileStream(@"c:\myfile.wmv", FileMode.OpenOrCreate,
                                                     FileAccess.Write);
fstr.Write(inBuf, 0, bytesRead);
reader.Close();
fstr.Close();