回複:用 playlist(xml) 快速下載更名工具

回答: 用 playlist(xml) 快速下載更名工具Clown1232012-03-07 18:35:25

Here is some C# code I wrote, which automatically parse the xml and download:

void Main()
{
	string xmlLink = @"http://space.wenxuecity.com/media/1331188562.xml";
	using(WebClient wc = new WebClient())
	{
		//var tracks = new ObservableCollection();
		wc.Headers["User-Agent"] = "Windows-Media-Player/11.0.5721.5145";
		string xml = wc.DownloadString(xmlLink);
		XDocument doc = XDocument.Parse(xml);
		XNamespace ns = "";
		if(xml.Contains("xmlns="))
		{
			Regex re = new Regex(@"xmlns=['|""](?[^\']*)['|""]", RegexOptions.Multiline);
			Match m  = re.Match(xml);
			if(m.Success)
				ns = m.Groups["ns"].Value;			
		}
		
		if(true)
		{
		var ParsedTracks = from t in doc.Descendants(ns+"track")
					 select new { location = t.Element(ns+"location").Value, annotation = t.Element(ns+"annotation").Value };
		
		List tasks = new List();
		foreach(var track in ParsedTracks)
		{	
		    var t = track;
			var task = Task.Factory.StartNew(() => {
			Download(t.location.Trim(), t.annotation.Trim());});
			tasks.Add(task);
		}
		Task.WaitAll(tasks.ToArray());
		}
		Console.WriteLine ("All done");
	}
}

// Define other methods and classes here

	public string cleanFileName(string originalFileName)
	{
		string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
		string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
		Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
		return r.Replace(originalFileName, "");
	}
	
	public string Download(string url, string fileName)
	{
		Uri uri = new Uri(url);
		string[] parts = url.Split(new char[]{'.'});
		string fileType = parts[ parts.Length - 1 ];
		string fileNameWithFullPath;		

		fileName = cleanFileName(fileName);
		
		const string DIR = @"C:\temp\music";
		if(!fileName.EndsWith(fileType))
			fileNameWithFullPath = string.Format(@"{0}\{1}.{2}", DIR, fileName, fileType);
		else 
			fileNameWithFullPath = string.Format(@"{0}\{1}", DIR, fileName);
		
		if(!Directory.Exists(DIR))
			Directory.CreateDirectory(DIR);
		
		if(File.Exists(fileNameWithFullPath))
		{
			Console.WriteLine ("File {0} exists, skip", fileName);
			return fileName + " is already downloaded";
		}
		
			Console.WriteLine ("-- {0}: {1}", fileName, url);
			using(WebClient cl = new WebClient())
			{
				cl.Headers["User-Agent"] = "Windows-Media-Player/11.0.5721.5145";
				Console.WriteLine ("Start dowloading {0}", url);			
				cl.DownloadFile(uri, fileNameWithFullPath);
			}
			//Thread.Sleep( TimeSpan.FromSeconds(5));
			Console.WriteLine ("File {0} downloaded", url);
			return fileName + " has been downloaded";
	}

所有跟帖: 

回複:回複:用 playlist(xml) 快速下載更名工具 -perldev- 給 perldev 發送悄悄話 (143 bytes) () 03/09/2012 postreply 05:15:24

請您先登陸,再發跟帖!