"когда я запускаю этот код, программа дважды пишет в текстовый файл, прежде чем распознает, что текст существует"
Основная проблема с вашим кодом в следующем состоянии:
for (int x = 0; x < lines.Length - 1; x++)
Вы перебираете все строки , за исключением последней , которая, вероятно, является той, которую вы ищете в данном случае.
Чтобы решить эту проблему, просто удалите - 1
из условия выхода.
При этом ваш код может быть значительно упрощен, если вы используете статические ReadLines
и AppendAllText
методы класса File
:
/// <summary>
/// Searches the specified file for the url and adds it if it doesn't exist.
/// If the specified file does not exist, it will be created.
/// </summary>
/// <param name="filePath">The path to the file to query.</param>
/// <param name="url">The url to search for and add to the file.</param>
/// <returns>True if the url was added, otherwise false.</returns>
protected static bool AddUrlIfNotExist(string filePath, string url)
{
if (!File.Exists(filePath)) File.Create(filePath).Close();
if (!File.ReadLines(filePath).Any(line => line.Contains(url)))
{
File.AppendAllText(filePath, url);
return true;
}
return false;
}
Тогда этот метод может быть использован в вашем коде как:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.F1) { Application.Exit(); return true; }
if (keyData == Keys.F2)
{
if (AddUrlIfNotExist("linkx.txt", webBrowser1.Url.AbsoluteUri))
{
MessageBox.Show("url copied!");
}
else
{
MessageBox.Show("there is a match");
}
}
// Call the base class
return base.ProcessCmdKey(ref msg, keyData);
}