使用后台工作程序将文本附加到另一个类的文本框中

时间:2014-09-27 11:26:21

标签: c# textbox backgroundworker

抱歉抱怨这么小的问题,但我无法找到解决方案。我创建了一个用于从Exchange服务器获取附件的类,以及用于添加服务器配置和表单的表单,我将其用于日志输出。我添加了backgroundWorker来创建单独的线程,当类获得正确的附件并收集输出信息时,它会重定向到backgroundWorker DoWork方法。问题是文本框的UI根本不想附加文本

下载附件的类看起来像:

namespace DownloadAttachmentExchange
{
    class ExchangeDwnClass
    {
    private string path_ = "";
    private string filterSender_ = "";
    private string subject_ = "";
    private string id_ = "";
    private string username_ = "";
    private string password_ = "";
    private string exchange_ = "";
    private string filterExcel_ = "";
    private string filterCSV_ = "";
    private string attachmentName_ = "";
    private int emailFetch_ = 0;
    private DateTime current_;

    ExchangeService serv = new ExchangeService(ExchangeVersion.Exchange2010_SP1);


    public string Path
    {
        get { return path_; }
        set { path_ = value; }
    }
    public string FilterSender
    {
        get { return filterSender_; }
        set { filterSender_ = value; }
    }
    public string Subject
    {
        get { return subject_; }
        set { subject_ = value; }
    }
    public string ID
    {
        get { return id_; }
        set { id_ = value; }
    }
    public string Username
    {
        get { return username_; }
        set { username_ = value; }
    }
    public string Password
    {
        get { return password_; }
        set { password_ = value; }
    }
    public string Exchange
    {
        get { return exchange_; }
        set { exchange_ = value; }
    }
    public string FilterExcel
    {
        get { return filterExcel_; }
        set { filterExcel_ = value; }    
    }
    public string FilterCsv
    {
        get { return filterCSV_; }
        set { filterCSV_ = value; }
    }
    public string AttachementName
    {
        get { return attachmentName_; }
        set { attachmentName_ = value; }
    }
    public int EmailFetch
    {
        get { return emailFetch_; }
        set { emailFetch_ = value; }
    }
    public DateTime CurrentDate
    {
        get { return current_; }
        set { current_ = value; }
    }

    public void GetAttachments()
    {
        try
        {  
            serv.Credentials = new WebCredentials(Username, Password);
            serv.AutodiscoverUrl(Exchange);

            ItemView view = new ItemView(10);
            FindItemsResults<Item> result = serv.FindItems(WellKnownFolderName.Inbox, new ItemView(EmailFetch));

            if (result != null && result.Items != null && result.Items.Count > 0)
            {
                foreach (Item item in result.Items)
                {
                    EmailMessage msg = EmailMessage.Bind(serv, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments, EmailMessageSchema.From, EmailMessageSchema.Sender));
                    if (msg.Sender.ToString().Contains(FilterSender) && msg.From.ToString().Contains(FilterSender))
                    {
                        foreach (Attachment att in msg.Attachments)
                        {
                            if (att is FileAttachment)
                            {
                                FileAttachment file = att as FileAttachment;
                                if (file.Name.Contains(FilterExcel) || file.Name.Contains(FilterCsv))
                                {
                                    Form1 form = new Form1();
                                    file.Load(Path +"\\"+ file.Name);
                                    AttachementName = file.Name.ToString();
                                    Subject = item.Subject.ToString();
                                    ID = item.Id.ToString();
                                    CurrentDate = DateTime.Now;                                 
                                    form.date = CurrentDate.ToString();
                                    form.subject = Subject;
                                    form.attachment = AttachementName;         
                                    form.backgroundWorker1.RunWorkerAsync();
                                    Thread.Sleep(60000);
                                }
                            }
                        }
                    }
                    //item.Delete(DeleteMode.HardDelete);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        Console.ReadLine();
    }
    public void StopDownloadingAttachment()
    { 

    }
}
}

表格如下:

namespace DownloadAttachmentExchange
{
public partial class Form1 : Form
{
    private string path = "";
    public string date = "";
    public string attachment = "";
    public string subject = "";
    public Form1()
    {
        InitializeComponent();
    }
    ExchangeDwnClass exchange = new ExchangeDwnClass();
    private void button3_Click(object sender, EventArgs e)
    {
        if(folderBrowserDialog1.ShowDialog(this)== DialogResult.OK)
        {
            path = folderBrowserDialog1.SelectedPath;   
            exchange.Path = path;
            pathTxt.Text = path;
        }
    }

    private void onBtn_Click(object sender, EventArgs e)
    {
        exchange.Username = userTxt.Text;
        exchange.Password = passwdTxt.Text;
        exchange.FilterSender = fromFilterTxt.Text;
        exchange.EmailFetch = Convert.ToInt32(fetchUpDown.Value);
        exchange.Exchange = exchangeTxt.Text;
        exchange.GetAttachments();
    }

    private void filterExcelCheck_CheckedChanged(object sender, EventArgs e)
    {
        if (filterExcelCheck.CheckState == CheckState.Checked)
        {
            exchange.FilterExcel = ".xlsx";
        }
        else
        {
            exchange.FilterExcel = "";
        }
    }

    private void filterCSVCheck_CheckedChanged(object sender, EventArgs e)
    {
        if (filterCSVCheck.CheckState == CheckState.Checked)
        {
            exchange.FilterCsv = ".csv";
        }
        else
        {
            exchange.FilterCsv = "";
        }
    }

    private void exchangeTxt_MouseHover(object sender, EventArgs e)
    {
        tipLbl.Visible = true;
        tipLbl.Text = "It is usually same as email address...";
    }

    private void exchangeTxt_MouseLeave(object sender, EventArgs e)
    {
        tipLbl.Visible = false;
    }
    //("\n" + CurrentDate.ToString() + " , Message id: " + ID + " , Message subject: " + Subject + " , Attachment name: " + AttachementName + "\r");
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        //e.Result = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
        logOutputTxt.Text = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
        //backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
    }

    //private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    //{
    //    if (e.Cancelled)
    //    {
    //        logOutputTxt.Text = "Thread is somehow cancelled, please contact developer for this issue...!";
    //    }
    //    else if (e.Error != null)
    //    {
    //        logOutputTxt.Text = e.Error.Message;
    //    }
    //    else
    //    {
    //        logOutputTxt.Text += e.Result;
    //    }
    //}
}
}

你可以看到我正在调用ExchangeDwnClass类的后台工作者,我认为可以使用:

  

form.backgroundWorker1.RunWorkerAsync();

当我运行调试器时,它真的会跳转到后台工作程序

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    logOutputTxt.Text = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
    //backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}

由于某种原因,表单文本框控件不刷新输出。 附:我也在RunWorkerCompleted方法上创建了但也没有运气......

有什么线索我可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

好的,问题是我在Form1的表单ExchangeDowClass中创建了另一个对象,而不是将引用对象传递给方法GetAttachments

complete code for Form1:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DownloadAttachmentExchange
{
public partial class Form1 : Form
{
    private string path = "";
    public string subject = "";
    public string attachment = "";
    public string date = "";
    public string sender = "";
    public Form1()
    {
        InitializeComponent();
    }
    ExchangeDwnClass exchange = new ExchangeDwnClass();
    BackgroundWorker bgrWorker = new BackgroundWorker();
    private void button3_Click(object sender, EventArgs e)
    {
        if(folderBrowserDialog1.ShowDialog(this)== DialogResult.OK)
        {
            path = folderBrowserDialog1.SelectedPath;   
            exchange.Path = path;
            pathTxt.Text = path;
        }
    }

    private void onBtn_Click(object sender, EventArgs e)
    {
        exchange.EmailFetch=Convert.ToInt32(fetchUpDown.Value);
        exchange.FilterSender = fromFilterTxt.Text;
        exchange.Exchange = exchangeTxt.Text;
        exchange.Password = passwdTxt.Text;
        exchange.Username = userTxt.Text;
        backgroundWorker1.RunWorkerAsync();
    }

    private void filterExcelCheck_CheckedChanged(object sender, EventArgs e)
    {
        if (filterExcelCheck.CheckState == CheckState.Checked)
        {
            exchange.FilterExcel = ".xlsx";
        }
        else
        {
            exchange.FilterExcel = "";
        }
    }

    private void filterCSVCheck_CheckedChanged(object sender, EventArgs e)
    {
        if (filterCSVCheck.CheckState == CheckState.Checked)
        {
            exchange.FilterCsv = ".csv";
        }
        else
        {
            exchange.FilterCsv = "";
        }
    }

    private void exchangeTxt_MouseHover(object sender, EventArgs e)
    {
        tipLbl.Visible = true;
        tipLbl.Text = "It is usually same as email address...";
    }

    private void exchangeTxt_MouseLeave(object sender, EventArgs e)
    {
        tipLbl.Visible = false;
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        //logOutputTxt.Text += "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r"
        //backgroundWorker1.ReportProgress(0);
        exchange.GetAttachments(this);
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
    }

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        logOutputTxt.Text += "\n" + date + " , Sender: "+sender+" , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
    }

}
}

和ExchangeDwnClass:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Exchange;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
using System.Threading;

namespace DownloadAttachmentExchange
{
class ExchangeDwnClass
{
    private string path_ = "";
    private string filterSender_ = "";
    private string subject_ = "";
    private string id_ = "";
    private string username_ = "";
    private string password_ = "";
    private string exchange_ = "";
    private string filterExcel_ = "";
    private string filterCSV_ = "";
    private string attachmentName_ = "";
    private int emailFetch_ = 0;
    private DateTime current_;

    ExchangeService serv = new ExchangeService(ExchangeVersion.Exchange2010_SP1);

    public string Path
    {
        get { return path_; }
        set { path_ = value; }
    }
    public string FilterSender
    {
        get { return filterSender_; }
        set { filterSender_ = value; }
    }
    public string Subject
    {
        get { return subject_; }
        set { subject_ = value; }
    }
    public string ID
    {
        get { return id_; }
        set { id_ = value; }
    }
    public string Username
    {
        get { return username_; }
        set { username_ = value; }
    }
    public string Password
    {
        get { return password_; }
        set { password_ = value; }
    }
    public string Exchange
    {
        get { return exchange_; }
        set { exchange_ = value; }
    }
    public string FilterExcel
    {
        get { return filterExcel_; }
        set { filterExcel_ = value; }    
    }
    public string FilterCsv
    {
        get { return filterCSV_; }
        set { filterCSV_ = value; }
    }
    public string AttachementName
    {
        get { return attachmentName_; }
        set { attachmentName_ = value; }
    }
    public int EmailFetch
    {
        get { return emailFetch_; }
        set { emailFetch_ = value; }
    }
    public DateTime CurrentDate
    {
        get { return current_; }
        set { current_ = value; }
    }

    public void GetAttachments(Form1 form)
    {
        try
        {  
            serv.Credentials = new WebCredentials(Username, Password);
            serv.AutodiscoverUrl("username@domain.lan");

            ItemView view = new ItemView(EmailFetch);
            FindItemsResults<Item> result = serv.FindItems(WellKnownFolderName.Inbox, new ItemView(EmailFetch));

            if (result != null && result.Items != null && result.Items.Count > 0)
            {
                foreach (Item item in result.Items)
                {
                    EmailMessage msg = EmailMessage.Bind(serv, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments, EmailMessageSchema.From, EmailMessageSchema.Sender));
                    if (msg.Sender.ToString().ToLower().Contains(FilterSender) && msg.From.ToString().ToLower().Contains(FilterSender))
                    {
                        foreach (Attachment att in msg.Attachments)
                        {
                            if (att is FileAttachment)
                            {
                                FileAttachment file = att as FileAttachment;
                                if (file.Name.Contains(FilterExcel) || file.Name.Contains(FilterCsv))
                                {
                                    file.Load(Path +"\\"+ file.Name);
                                    form.attachment = file.Name.ToString();
                                    form.subject = item.Subject.ToString();
                                    //ID = item.Id.ToString();
                                    form.date = DateTime.Now.ToString();
                                    form.sender = msg.Sender.ToString();
                                    form.backgroundWorker1.ReportProgress(0);
                                    Thread.Sleep(60000);
                                }
                            }
                        }
                    }
                    //item.Delete(DeleteMode.HardDelete);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        Console.ReadLine();
    }
    public void StopDownloadingAttachment()
    { 

    }
}
}

另外,我必须使用ProgressChanged方法来刷新控制... 我仍然有一些小错误,如文本框形式的双输出,但这基本上是小问题。 我希望这段代码对其他人有用。

干杯。