在C#中,我想从URL代码中找到一个PHP变量
示例:我想从text
中找到www.domain.com/file.php?var=text
主要原因是我想解析
的输出
youtube.com/get_video_info?video_id=
或System.IO.Path.GetTempPath() + @"\tempytinfo.txt"
,其格式为:
?var=value&var2=value&var3=value&
...
我试图解决这个问题的努力是坐在谷歌,调试其他答案,或者不工作或者不是我正在寻找的东西,这是我迄今为止的努力(也是在第一个awnser的帮助下):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Paste A YouTube URL/URI to Download:");
string yturlstr = Console.ReadLine();
Uri yturl = new Uri(yturlstr);
Console.WriteLine("Finding ID in YouTube URL...");
string ytid = yturlstr.Split('?')[1];
ytid = ytid.Replace("v=", "");
Console.WriteLine("Found Watch ID.");
Console.WriteLine("The " + '"' + "Watch ID" + '"' + " is " + ytid);
Console.WriteLine("Getting Video Info...");
Download("http://youtube.com/get_video_info?video_id=" + ytid, System.IO.Path.GetTempPath() + @"\tempytinfo.txt");
Console.WriteLine("Got Info.");
Console.WriteLine("Reading Video Info...");
string viddata = System.IO.File.ReadAllText(System.IO.Path.GetTempPath() + @"\tempytinfo.txt");
Console.WriteLine("Parsing Video Info...");
Dictionary<string, string> videodata = new Dictionary<string, string>();
string vdt = viddata;
string[] vdata = vdt.Split('&');
foreach (char param in vdt)
{
string[] paramParts = char.ToString(param).Split('=');
videodata.Add(paramParts[0], paramParts[1]);
}
string uefsm = WebUtility.UrlDecode(videodata["url_encoded_fmt_stream_map"]);
Dictionary<string, string> videosubdata = new Dictionary<string, string>();
string[] vsdata = uefsm.Split('&');
foreach (char param2 in uefsm)
{
string[] paramParts2 = char.ToString(param2).Split('=');
videosubdata.Add(paramParts2[0], paramParts2[1]);
}
Uri downloadlink = new Uri(WebUtility.UrlDecode(videosubdata["url"]));
Console.WriteLine("Download Link: " + '"' + downloadlink + '"');
Console.ReadKey();
}
private static void Download(string URL, string WhereToDownload)
{
var client = new WebClient();
Uri downloadurl = new Uri(URL);
client.DownloadFile(downloadurl, WhereToDownload);
}
}
}
我的错误是:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in ConsoleApplication2.exe
Additional information: Index was outside the bounds of the array.
答案 0 :(得分:1)
我会解析所有参数并将它们存储在一个集合中以便轻松访问它们。假设您在yturl
中拥有与代码相同的URL,则可以创建集合:
Dictionary<string, string> parameters = new Dictionary<string, string>();
string tmpStr = yturl.Split('?')[1];
string[] params = tmpStr.Split('&');
foreach (string param in params)
{
string[] paramParts = param.Split('=');
parameters.Add(paramParts[0], paramParts[1]);
}
按照你的例子,获得“text”,然后:
string var = parameters["var"];
// var == "text"
以及其名称的任何其他参数值:
string var1 = parameters["var1"];
string var2 = parameters["var2"];