简体   繁体   English

文本未附加到RichTextBox

[英]Text Not Appending To RichTextBox

I have been working on this issue for the past few days with no luck on a solution, i don't see where in the code i could have gone wrong, in a background worker, i am using a for loop to request adata from my server, which it returns fine, in my testing it loops 5 times, what it should do is on each iteration of the loop append the data to a richTextBox but with everything i have tried it keeps over writing the data in the richTextBox: 在过去的几天里,我一直在解决这个问题,但没有运气,在后台工作人员中,我看不到代码中哪里出了错,我正在使用for循环从我的设备请求数据服务器,它返回的很好,在我的测试中它循环了5次,它应该做的是在循环的每次迭代中将数据追加到richTextBox中,但是我尝试过的所有方法都使数据不断地写入richTextBox中:

Code: 码:

    private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
    {

        string action = e.Argument as string;

        if (action == "wraith_create_project")
        {

            StringBuilder sb = new StringBuilder();

            // NEEDED FOR FORMAT PURPOSES //
            var separator = Environment.NewLine;
            const string gsaSeparator = "\x01";

            // VARS //
            var articleSource = "";
            var articlekeywrd = "";
            var title = "";
            var body = "";
            var hash = "";
            var gsaArticleInfo = "";
            var richTextBoxText = "";

            // BREAK MAIN THREAD TO GET UI VALUES //
            Invoke(new MethodInvoker(() => { articleSource = comboBoxArticleSources.Text; }));
            Invoke(new MethodInvoker(() => { articlekeywrd = txtBoxScrapeKeyword.Text; }));

            try
            {
                // BREAK THREAD UPDATE UI LOG //
                Invoke(new MethodInvoker(() => { listBoxMain.Items.Add("[" + DateTime.Now + "] Building project ... " + articlekeywrd); }));

                if (articleSource == "Internal Article Builder")
                {

                        for (int x = 0; x <= 5; x++ ) {

                            // EVERY LOOP REQUESTS AN ARTICLE WHICH IS RETURNED AT RAND() //
                            var requestArticles = Helpers.getArticleTitleAndBodyInternalSpinner("https://www.thesite.com/api.php?articleBuilder=1&q=" + articlekeywrd.Replace(" ", "_"));

                            title = Helpers.internalSpinner(requestArticles.Item1); // SEND TO INTERNAL SPINNER FOR SPINNING ...
                            body  = Helpers.internalSpinner(requestArticles.Item2); // SEND TO INTERNAL SPINNER FOR SPINNING ...
                            hash  = To32BitFnv1aHash(body).ToString("X8");

                            // NEED A SMALL 5 SECOND SLEEP TO BE GOOD TO THE SERVER //
                            System.Threading.Thread.Sleep(5000);

                            Invoke(new MethodInvoker(() =>
                            {
                                listBoxMain.Items.Add("[" + DateTime.Now + "] Returned article ... " + requestArticles.Item1);
                                listBoxMain.Items.Add("[" + DateTime.Now + "] Spun the article ... " + title);
                                listBoxMain.Items.Add("[" + DateTime.Now + "] Pausing 5 seconds ... ");
                            }));

                            // ENCODE WITH THE GSA SEPERATOR BETWEEN EACH FIELD //
                            gsaArticleInfo = title + gsaSeparator + "%first_paragraph-article%"  + gsaSeparator + body + gsaSeparator + hash;

                            // ADD TO THE RICHTEXTBOX ALL FIELDS FROM ABOVE //
                            richTextBoxText = string.Join(separator, gsaArticleInfo);

                            // ADD THE RETURNED AND SPUN ARTICLES TO THE RICHTEXTBOX //
                            Invoke(new MethodInvoker(() => { richTxtBoxArticle.Text += richTextBoxText; }));

                            // TESTING //
                            File.WriteAllText(@"debug.txt", richTextBoxText);

                    } // End for loop.

                } else if (articleSource == "") {
                       // RESERVED FOR ADDITIONAL SOURCES //                    
                }

            } catch (Exception ex) {
                Helpers.returnMessage(ex.ToString());
            }

        }
    }

Updated Function: 更新功能:

    public static Tuple<string, string> getArticleTitleAndBodyInternalSpinner(string url)
    {

        // SETUP HTML VAR AND TUPLE //
        string page = null;
        Tuple<string, string> result = null;

        // TRY/CATCH //
        try
        {
            using (WebClient wc = new WebClient())
            {
                // THE WEBPAGE //
                page = wc.DownloadString(url);
            }

            var articleT = "";
            var articleB = "";

            MatchCollection aTitle = Regex.Matches(page, @"<span class='articleTitle'>(.*?)</span>", RegexOptions.Singleline);
            var post1 = "";
            foreach (Match aTitleMatch in aTitle) {
                post1 = aTitleMatch.Groups[1].Value;
            }
            articleT = post1;

            MatchCollection aBody = Regex.Matches(page, @"<span class='articleBody'>(.*?)</span>", RegexOptions.Singleline);
            var post2 = "";
            foreach (Match aBodyMatch in aBody)
            {
                post2 = aBodyMatch.Groups[1].Value;
            }
            articleB = post2;

            // ADD THE ARTICLE TITLE AND BODY TO THE TUBLE //
            result = Tuple.Create(articleT, articleB);

        } catch (Exception ex) {
            returnMessage("INTERNAL ARTICLE BUILDER: \n\n" + ex.ToString());
        }
        return result;
    }

I have tried writing to a .txt file within the loop (it keeps getting overwritten too) it just will not append, AppendText , += , stringbuilders, everything seems to be the same, the data is coming through as it should from title, body, hash but it just will not append, can anyone see any obvious mistakes i have made? 我试过在循环中写入.txt文件(它也不断被覆盖),只是不会追加, AppendText+=AppendText ,似乎一切都一样,数据正好从标题通过,正文,哈希,但不会追加,有人可以看到我犯的任何明显错误吗? is it maybe the background worker is deleting each iteration text causing this? 难道后台工作者正在删除导致此问题的每个迭代文本? nothing much is coming up when i search it seems, any help is appreciated. 当我进行搜索时,没有任何进展,任何帮助都值得赞赏。

It's possible that the text you're trying to append is larger than the MaxLength property of the RichTextBox . 您尝试添加的文本可能大于RichTextBoxMaxLength属性。 I recommend checking this property and ensuring it's set to a value large enough to accommodate all of your text. 我建议检查此属性,并确保将其设置为足够大的值以容纳所有文本。 Here's an example of how to perform this check (code snippet from the link below): 这是如何执行此检查的示例(以下链接中的代码段):

private void AddMyText(string textToAdd)
{
    // Determine if the text to add is larger than the max length property.
    if (textToAdd.Length > richTextBox1.MaxLength)
        // Alert user text is too large.
        MessageBox.Show("The text is too large to addo to the RichTextBox");
    else
        // Add the text to be added to the control.
        richTextBox1.SelectedText = textToAdd;
}

You can read more here: 你可以在这里阅读更多:

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.richtextbox.maxlength?view=netframework-4.7.2 https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.richtextbox.maxlength?view=netframework-4.7.2

Also, because you're using File.WriteAllText() instead of File.AppendAllText() debug.txt will only contain the contents of the string that was last written. 另外,由于您使用的是File.WriteAllText()而不是File.AppendAllText() debug.txt仅包含最后写入的字符串的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM