【发布时间】:2012-02-09 17:24:57
【问题描述】:
我修改了一个用 C# 编写的 Youtube Downloader 类,以便在 Windows 手机上使用它。我的结果如下。但是当我调用 dw();我在 e.Result.Read(buffer, 0, buffer.Length) 行中从 Web 浏览器获得了一个 File-not-found-exception。我当然知道这意味着什么,但我不知道如何解决它。所以我有两个问题:为什么我的代码不起作用?或者还有其他方法可以在 WindowsPhone 7 上下载 Youtube 视频吗? (比如图书馆或免费代码 sn-p...)谢谢。
class YoutubeDownload
{
string youtubeurl;
string fileext;
private WebClient webClient = new WebClient();
public void dw()
{
youtubeurl = "http://www.youtube.com/watch?v=locIxsfpgp4&feature=related";
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(youtubeurl));
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string rawHtml = e.Result;
string getUrl = "http://www.youtube.com/get_video.php?video_id={0}&t={1}";
Regex _titleRegex = new Regex("'VIDEO_TITLE': '(.+)',");
Regex _qualiRegex = new Regex("\"fmt_map\": \"([0-9]{2})");
Regex _idRegex = new Regex("\",\\s*\"t\":\\s*\"([^\"]+)");
Match title = _titleRegex.Match(rawHtml);
Match id = _idRegex.Match(rawHtml);
Match quali = _qualiRegex.Match(rawHtml);
string videotitle = title.Groups[1].Value;
string videoid = youtubeurl.Substring(youtubeurl.IndexOf("?v=") + 3);
string id2 = id.Groups[1].Value.Replace("%3D", "=");
string dlurl = string.Format(getUrl, videoid, id2);
fileext = "flv";
if (rawHtml.Contains("'IS_HD_AVAILABLE': true")) // 1080p/720p
{
dlurl += "&fmt=" + quali.Groups[1].Value;
fileext = "mp4";
}
else
{
dlurl += "&fmt=" + quali.Groups[1].Value;
if (quali.Groups[1].Value == "18") // Medium
fileext = "mp4";
else if (quali.Groups[1].Value == "17") // Mobile
fileext = "3gp";
}
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
webClient.OpenReadAsync(new Uri(dlurl));
}
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
var file = IsolatedStorageFile.GetUserStoreForApplication();
file.CreateDirectory("YoutubeDownloader");
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("file." + fileext, System.IO.FileMode.Create, file))
{
byte[] buffer = new byte[1024];
while (e.Result.Read(buffer, 0, buffer.Length) > 0)
{
stream.Write(buffer, 0, buffer.Length);
}
}
}
}
【问题讨论】:
-
除此之外,你的“复制”方法是不正确的——你总是写
buffer.Length字节,即使你读的比这少…… -
当你调用
Read时,你应该记住结果,这样你就可以在调用中使用它来写:while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)... -
谢谢 - 你真的帮助了我。 - 但我无法将问题标记为已解决,因为您“只”写了评论,可以吗?
-
那一切都是错的吗?好的,我把它写下来作为答案......
-
我没有收到错误代码 - 但我也没有 windows-phone,所以我不知道它是否真的有效。
标签: c# windows-phone-7 download