c# - 如何使用 IndexOf 和 Substring 从字符串中解析文件名?

标签 c# .net string substring indexof

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/

相关文章:

c# - MySQL 站点搜索中参数化查询的问题

.net - 这似乎是并发集合/队列组合的合理方法吗?

string - Clojure 中搜索字符串向量

c# - GenerateChangePhoneNumberToken System.ArgumentNullException : String reference not set to an instance of a String. 参数名称:s

javascript - 在代码隐藏中调用 Web 方法

c# - 将 C# 字符串与 '==' 进行比较是一种好习惯吗?

c# - 解析日志文件时性能下降

c++ - 将 uint8 转换为字符串

Java:字符串数组;尝试将字符串作为代码执行

关于 "this"关键字的 C# 快速问题?