Проверьте, существует ли текст в текстовом файле - PullRequest
0 голосов
/ 30 августа 2018

Я пытаюсь выяснить, существует ли текстовый URL, который я получаю с текущего URL, в 'linkx.txt', если он показывает сообщение, если он не записывает текстовый файл. однако, когда я запускаю этот код, программа дважды пишет в текстовый файл, прежде чем распознает существующий текст.

[рабочий код]

  protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    string linkx = @"Desktop\linkx.txt";
    string url = "";
    if (keyData == Keys.F1) { Application.Exit(); return true; }
    else if (keyData == Keys.F2) { url = webBrowser1.Url.AbsoluteUri; return true; }

    using (StreamReader sr = File.OpenText(linkx))
    {
        string texxt = url;
        string[] lines = File.ReadAllLines(linkx);
        bool matched = false;
        for (int x = 0; x < lines.Length; x++)
        {
            if (texxt == lines[x])
            {
                sr.Close();
                MessageBox.Show("there is a match");
                matched = true;
            }
        }
        if (!matched)
        {
            sr.Close();
            using (StreamWriter wriite = File.AppendText(linkx))
            {
                wriite.WriteLine(url);
                MessageBox.Show("url copied!");
                return true;    // indicate that you handled this keystroke
            }
        }
    }
    // Call the base class
    return base.ProcessCmdKey(ref msg, keyData);
}

Ответы [ 2 ]

0 голосов
/ 30 августа 2018

"когда я запускаю этот код, программа дважды пишет в текстовый файл, прежде чем распознает, что текст существует"

Основная проблема с вашим кодом в следующем состоянии:

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);
}
0 голосов
/ 30 августа 2018

Это намного проще, чем у вас есть. Если у вас есть только массив строк, вы можете использовать Array.Contains .

var lines = File.ReadAllLines("links.txt");

if (!lines.Contains("google.com")) {
  File.AppendAllText("links.txt", "google.com");
}
...