我正在尝试遍历文件中的每一行,这是一个链接。然后我添加一个字符串列表所有死链接(返回404的链接或在页面上打印一个特定的短语。到目前为止一切正常,但我目前面临的唯一问题是它不会从文件中删除它们正如我要求接近结束。
为什么会这样?
using System.Collections.Generic;
namespace dead_link_finder
{
using System;
using System.IO;
using System.Net;
using System.Threading;
static class Program
{
private static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.White;
var fileToScan = Console.ReadLine();
var reader = new StreamReader(fileToScan);
string line;
var deadLinks = new List<string>();
while ((line = reader.ReadLine()) != null)
{
Log("Scanning: " + line, ConsoleColor.White);
using (var webClient = new WebClient())
{
try
{
var content = webClient.DownloadString(line);
if (content.Contains("text-danger"))
{
deadLinks.Add(line);
}
}
catch (WebException wex)
{
if (((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
{
deadLinks.Add(line);
}
}
}
}
reader.Close();
Console.WriteLine();
Console.WriteLine("Found: " + deadLinks.Count + " dead links in the collection.");
Console.WriteLine();
Thread.Sleep(5000);
Console.WriteLine("Removing the dead links, please wait...");
foreach (var deadLink in deadLinks)
{
var str = File.ReadAllText(fileToScan);
File.WriteAllText(fileToScan, str.Replace(deadLink, ""));
}
Console.WriteLine();
Console.WriteLine("Finished...");
Console.ReadKey(true);
}
}
}
答案 0 :(得分:0)
你可以试试这个。将文件内容解析为列表,将死链接保存在另一个链接中,然后使用LINQ扩展方法ReadFile()
来获取差异。
这段代码有点混乱,并试图一次性做很多事情。您应该将其拆分为更易于管理的内容,例如CheckLinks()
,WriteFile()
和using System.Collections.Generic;
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Linq;
namespace dead_link_finder
{
static class Program
{
private static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.White;
var fileToScan = Console.ReadLine();
var links = File.ReadAllLines(fileToScan);
var deadLinks = new List<string>();
var webClient = new WebClient();
foreach (var link in links)
{
try
{
var content = webClient.DownloadString(link);
if (content.Contains("text-danger"))
{
deadLinks.Add(link);
}
}
catch (WebException wex)
{
if (wex.Status == WebExceptionStatus.NameResolutionFailure )
{
deadLinks.Add(link);
}
}
}
Console.WriteLine();
Console.WriteLine("Found: " + deadLinks.Count + " dead links in the collection.");
Console.WriteLine();
Thread.Sleep(5000);
Console.WriteLine("Removing the dead links, please wait...");
var justTheGoodLinks = links.Except(deadLinks);
File.WriteAllLines(fileToScan, justTheGoodLinks);
Console.WriteLine();
Console.WriteLine("Finished...");
Console.ReadKey(true);
}
}
}
等。
{{1}}