private void ParseFilesNames()
{
using (WebClient client = new WebClient())
{
try
{
for (int i = 0; i < 15; i++)
{
string urltoparse = "mysite.com/gallery/albums/from_old_gallery/" + i;
string s = client.DownloadString(urltoparse);
int index = -1;
while (true)
{
string firstTag = "HREF=";
string secondtag = ">";
index = s.IndexOf(firstTag, 0);
int endIndex = s.IndexOf(secondtag, index);
if (index < 0)
{
break;
}
else
{
string filename = s.Substring(index + firstTag.Length, endIndex - index - firstTag.Length);
}
}
}
}
catch (Exception err)
{
}
}
}
问题出在子串上。 index + firstTag.Length, endIndex - index - firstTag.Length 这是错误的。
我需要获取的是:HREF="
和 ">
整个字符串如下所示:HREF="myimage.jpg">
我只需要获取“myimage.jpg”
有时它可以是“myimage465454.jpg”所以在任何情况下我只需要获取文件名。只有“myimage465454.jpg”。
我应该在子字符串中更改什么?
最佳答案
如果您确定您的字符串将始终是
string yourInitialString = @"HREF="myimage.jpg"";
string parsedString = yourInitialString.Replace(@"<HREF="").Replace(@"">");
如果您需要解析 HTML 链接 href 值,最好的选择是使用 HtmlAgilityPack图书馆。
使用 Html Agility Pack 的解决方案:
HtmlWeb htmlWeb = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = htmlWeb.Load(Url);
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
{
// Get the value of the HREF attribute
string hrefValue = link.GetAttributeValue( "href", string.Empty );
}
要安装 HtmlAgilityPack,请在包管理器控制台中运行以下命令:
PM> Install-Package HtmlAgilityPack
希望对您有所帮助。
关于c# - 如何使用 IndexOf 和 Substring 从字符串中解析文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27791147/