gpt4 book ai didi

c# - 如何使用 WebResponse 下载 .wmv 文件

转载 作者:太空狗 更新时间:2023-10-29 22:25:05 24 4
gpt4 key购买 nike

我正在使用以下代码通过 WebResponse 获取 wmv 文件。我正在使用一个线程来调用这个函数:

static void GetPage(object data)
{
// Cast the object to a ThreadInfo
ThreadInfo ti = (ThreadInfo)data;

// Request the URL
WebResponse wr = WebRequest.Create(ti.url).GetResponse();

// Display the value for the Content-Length header
Console.WriteLine(ti.url + ": " + wr.Headers["Content-Length"]);
string toBeSaved = @"C:\Users\Kevin\Downloads\TempFiles" + wr.ResponseUri.PathAndQuery;
StreamWriter streamWriter = new StreamWriter(toBeSaved);

MemoryStream m = new MemoryStream();
Stream receiveStream = wr.GetResponseStream();
using (StreamReader sr = new StreamReader(receiveStream))
{
while (sr.Peek() >= 0)
{
m.WriteByte((byte)sr.Read());
}
streamWriter.Write(sr.ReadToEnd());
sr.Close();
wr.Close();
}

streamWriter.Flush();
streamWriter.Close();

// streamReader.Close();
// Let the parent thread know the process is done
ti.are.Set();

wr.Close();
}

文件似乎可以正常下载,但 Windows Media Viewer 无法正确打开文件。关于无法支持文件类型的一些愚蠢的错误。

我错过了什么非常简单的事情?

最佳答案

您只需将其下载为二进制文件而不是文本文件。这里有一个方法应该可以为您解决问题。

public void DownloadFile(string url, string toLocalPath)
{
byte[] result = null;
byte[] buffer = new byte[4097];

WebRequest wr = WebRequest.Create(url);

WebResponse response = wr.GetResponse();
Stream responseStream = response.GetResponseStream;
MemoryStream memoryStream = new MemoryStream();

int count = 0;

do {
count = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, count);

if (count == 0) {
break;
}
}
while (true);

result = memoryStream.ToArray;

FileStream fs = new FileStream(toLocalPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);

fs.Write(result, 0, result.Length);

fs.Close();
memoryStream.Close();
responseStream.Close();
}

关于c# - 如何使用 WebResponse 下载 .wmv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1183698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com