使用filewatcher C#自动刷新列表框

时间:2013-07-18 00:51:28

标签: c# file text listbox refresh

好的,我已经有一段时间了。我有一个程序监视一个文件“lab.txt”的更改,当它发生更改时,我希望它将文件的内容重新加载到显示的列表框中。我可以让它显示并告诉我什么时候有变化,但我不能让列表框刷新。任何帮助都会受到谴责。现在有很多代码没有被使用,因为我一直在尝试不同的方法,所以请不要理会。

namespace FileChangeNotifier
{

public partial class frmNotifier : Form
{
    private StringBuilder m_Sb;
    private bool m_bDirty;
    private System.IO.FileSystemWatcher m_Watcher;
    private bool m_bIsWatching;
    public static string txtPath = "E:/lab.txt";
    List<string> list;
    BindingList<string> bindingList;

    public frmNotifier()
    {
        InitializeComponent();
        m_Sb = new StringBuilder();
        m_bDirty = false;
        m_bIsWatching = false;
        //BindingSource bindingSource = (BindingSource)listBox1.DataSource;
       // List SourceList = (List)bindingSource.List;
        list= new List<string>(File.ReadLines(txtPath));
        bindingList = new BindingList<string>(list);
        listBox1.DataSource = bindingList;
        //listBox1.SelectedIndex = -1;

        m_bIsWatching = true;
        btnWatchFile.BackColor = Color.Red;
        m_Watcher = new System.IO.FileSystemWatcher();

        m_Watcher.Filter = "lab.txt";
        m_Watcher.Path = "E:\\";


        m_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                             | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        m_Watcher.Changed += new FileSystemEventHandler(OnChanged);
        m_Watcher.Created += new FileSystemEventHandler(OnChanged);
        m_Watcher.Deleted += new FileSystemEventHandler(OnChanged);
        m_Watcher.Renamed += new RenamedEventHandler(OnRenamed);
        m_Watcher.EnableRaisingEvents = true;
    }

    private void btnWatchFile_Click(object sender, EventArgs e)
    {
        if (m_bIsWatching)
        {
            m_bIsWatching = false;
            m_Watcher.EnableRaisingEvents = false;
            m_Watcher.Dispose();
            btnWatchFile.BackColor = Color.LightSkyBlue;
            btnWatchFile.Text = "Start Watching";

        }
        else
        {
            m_bIsWatching = true;
            btnWatchFile.BackColor = Color.Red;
            btnWatchFile.Text = "Stop Watching";

            m_Watcher = new System.IO.FileSystemWatcher();
          //if (rdbDir.Checked)
           //
                m_Watcher.Filter = "lab.txt";
                m_Watcher.Path = "E:\\";
            //
           /*lse
            {
                m_Watcher.Filter = txtFile.Text.Substring(txtFile.Text.LastIndexOf('\\') + 1);
                m_Watcher.Path = txtFile.Text.Substring(0, txtFile.Text.Length - m_Watcher.Filter.Length);
            }

            if (chkSubFolder.Checked)
            {
                m_Watcher.IncludeSubdirectories = true;
            }*/

            m_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                 | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            m_Watcher.Changed += new FileSystemEventHandler(OnChanged);
            m_Watcher.Created += new FileSystemEventHandler(OnChanged);
            m_Watcher.Deleted += new FileSystemEventHandler(OnChanged);
            m_Watcher.Renamed += new RenamedEventHandler(OnRenamed);
            m_Watcher.EnableRaisingEvents = true;
        }
    }

    private void OnChanged(object sender, FileSystemEventArgs e)
    {
        if (!m_bDirty)
        {
            m_Sb.Remove(0, m_Sb.Length);
            m_Sb.Append(e.FullPath);
            m_Sb.Append(" ");
            m_Sb.Append(e.ChangeType.ToString());
            m_Sb.Append("    ");
            m_Sb.Append(DateTime.Now.ToString());
            m_bDirty = true;



        }
    }

    private void OnRenamed(object sender, RenamedEventArgs e)
    {
        if (!m_bDirty)
        {
            m_Sb.Remove(0, m_Sb.Length);
            m_Sb.Append(e.OldFullPath);
            m_Sb.Append(" ");
            m_Sb.Append(e.ChangeType.ToString());
            m_Sb.Append(" ");
            m_Sb.Append("to ");
            m_Sb.Append(e.Name);
            m_Sb.Append("    ");
            m_Sb.Append(DateTime.Now.ToString());
            m_bDirty = true;

        }            
    }

    private void tmrEditNotify_Tick(object sender, EventArgs e)
    {
        if (m_bDirty)
        {
            lstNotification.BeginUpdate();
            lstNotification.Items.Add(m_Sb.ToString());
            lstNotification.EndUpdate();
            m_bDirty = false;
        }
    }

    private void btnBrowseFile_Click(object sender, EventArgs e)
    {

    }

    private void btnLog_Click(object sender, EventArgs e)
    {
        DialogResult resDialog = dlgSaveFile.ShowDialog();
        if (resDialog.ToString() == "OK")
        {
            FileInfo fi = new FileInfo(dlgSaveFile.FileName);
            StreamWriter sw = fi.CreateText();
            foreach (string sItem in lstNotification.Items)
            {
                sw.WriteLine(sItem);
            }
            sw.Close();
        }
    }


    public void bindData()
    {




        listBox1.DataSource = null;
        bindingList=null;
        list = new List<string>(File.ReadLines(txtPath));
        bindingList = new BindingList<string>(list);
        listBox1.DataSource = bindingList;

    }

private void Execute(object sender, EventArgs e)
    {
        string task = TaskQue.Pop();
        //execute task;
        listBox1.DataSource = TaskQue.GetTasks();
    }

    private void AddTask(object sender, EventArgs e)
    {
        TaskQue.Push(listBox1.Text);
        listBox1.DataSource = TaskQue.GetTasks();

    }

    private void txtFile_TextChanged(object sender, EventArgs e)
    {

    }

    private void lstNotification_SelectedIndexChanged(object sender, EventArgs e)
    {


    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}

public class TaskQue
{
    public static string txtPath = "E:/lab.txt";

    public static string Pop()
    {
        StreamReader sr = new StreamReader(txtPath);
        string result = sr.ReadLine();
        string remaining = sr.ReadToEnd();
        sr.Close();
        StreamWriter sw = new StreamWriter(txtPath, false);
        sw.Write(remaining);
        sw.Close();
        return result;
    }

    public static void Push(string s)
    {

        StreamWriter sw = new StreamWriter(txtPath, true);
        sw.WriteLine(s);
        sw.Close();
    }

    public static IEnumerable<string> GetTasks()
    {
        return new List<string>(File.ReadLines(txtPath));

    }
} 




}

编辑:

这是我改变了但仍然没有去

 private void OnChanged(object sender, FileSystemEventArgs e)
    {
        if (!m_bDirty)
        {
            m_Sb.Remove(0, m_Sb.Length);
            m_Sb.Append(e.FullPath);
            m_Sb.Append(" ");
            m_Sb.Append(e.ChangeType.ToString());
            m_Sb.Append("    ");
            m_Sb.Append(DateTime.Now.ToString());
            m_bDirty = true;
            list = new List<string>(File.ReadAllLines(txtPath));
            bindingList = new BindingList<string>(list);
            listBox1.DataSource = bindingList;
        }
    }

这是我的Form.Designer.cs文件

namespace FileChangeNotifier
{
partial class frmNotifier
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.btnWatchFile = new System.Windows.Forms.Button();
        this.lstNotification = new System.Windows.Forms.ListBox();
        this.label3 = new System.Windows.Forms.Label();
        this.tmrEditNotify = new System.Windows.Forms.Timer(this.components);
        this.dlgOpenFile = new System.Windows.Forms.OpenFileDialog();
        this.dlgOpenDir = new System.Windows.Forms.FolderBrowserDialog();
        this.btnLog = new System.Windows.Forms.Button();
        this.dlgSaveFile = new System.Windows.Forms.SaveFileDialog();
        this.listBox1 = new System.Windows.Forms.ListBox();
        this.frmNotifierBindingSource = new System.Windows.Forms.BindingSource(this.components);
        ((System.ComponentModel.ISupportInitialize)(this.frmNotifierBindingSource)).BeginInit();
        this.SuspendLayout();
        // 
        // btnWatchFile
        // 
        this.btnWatchFile.BackColor = System.Drawing.Color.LightSkyBlue;
        this.btnWatchFile.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
        this.btnWatchFile.ForeColor = System.Drawing.SystemColors.ControlText;
        this.btnWatchFile.Location = new System.Drawing.Point(15, 165);
        this.btnWatchFile.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
        this.btnWatchFile.Name = "btnWatchFile";
        this.btnWatchFile.Size = new System.Drawing.Size(159, 28);
        this.btnWatchFile.TabIndex = 4;
        this.btnWatchFile.Text = "Start Watching";
        this.btnWatchFile.UseVisualStyleBackColor = false;
        this.btnWatchFile.Click += new System.EventHandler(this.btnWatchFile_Click);
        // 
        // lstNotification
        // 
        this.lstNotification.FormattingEnabled = true;
        this.lstNotification.ItemHeight = 16;
        this.lstNotification.Location = new System.Drawing.Point(15, 228);
        this.lstNotification.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
        this.lstNotification.Name = "lstNotification";
        this.lstNotification.Size = new System.Drawing.Size(613, 276);
        this.lstNotification.TabIndex = 5;
        this.lstNotification.SelectedIndexChanged += new System.EventHandler(this.lstNotification_SelectedIndexChanged);
        // 
        // label3
        // 
        this.label3.AutoSize = true;
        this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.label3.Location = new System.Drawing.Point(15, 208);
        this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
        this.label3.Name = "label3";
        this.label3.Size = new System.Drawing.Size(158, 17);
        this.label3.TabIndex = 6;
        this.label3.Text = "Change Notifications";
        // 
        // tmrEditNotify
        // 
        this.tmrEditNotify.Enabled = true;
        this.tmrEditNotify.Tick += new System.EventHandler(this.tmrEditNotify_Tick);
        // 
        // dlgOpenDir
        // 
        this.dlgOpenDir.RootFolder = System.Environment.SpecialFolder.MyComputer;
        // 
        // btnLog
        // 
        this.btnLog.BackColor = System.Drawing.SystemColors.Highlight;
        this.btnLog.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
        this.btnLog.Location = new System.Drawing.Point(15, 519);
        this.btnLog.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
        this.btnLog.Name = "btnLog";
        this.btnLog.Size = new System.Drawing.Size(159, 28);
        this.btnLog.TabIndex = 9;
        this.btnLog.Text = "Dump To Log";
        this.btnLog.UseVisualStyleBackColor = false;
        this.btnLog.Click += new System.EventHandler(this.btnLog_Click);
        // 
        // dlgSaveFile
        // 
        this.dlgSaveFile.DefaultExt = "log";
        this.dlgSaveFile.Filter = "LogFiles|*.log";
        // 
        // listBox1
        // 
        this.listBox1.DataSource = this.frmNotifierBindingSource;
        this.listBox1.FormattingEnabled = true;
        this.listBox1.ItemHeight = 16;
        this.listBox1.Location = new System.Drawing.Point(807, 74);
        this.listBox1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
        this.listBox1.Name = "listBox1";
        this.listBox1.Size = new System.Drawing.Size(277, 388);
        this.listBox1.TabIndex = 10;
        this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
        // 
        // frmNotifierBindingSource
        // 
        this.frmNotifierBindingSource.DataSource = typeof(FileChangeNotifier.frmNotifier);
        // 
        // frmNotifier
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(1207, 562);
        this.Controls.Add(this.listBox1);
        this.Controls.Add(this.btnLog);
        this.Controls.Add(this.label3);
        this.Controls.Add(this.lstNotification);
        this.Controls.Add(this.btnWatchFile);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
        this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
        this.MaximizeBox = false;
        this.Name = "frmNotifier";
        this.Text = "File/Directory Change Notifier";
        ((System.ComponentModel.ISupportInitialize)(this.frmNotifierBindingSource)).EndInit();
        this.ResumeLayout(false);
        this.PerformLayout();

    }

    #endregion

    private System.Windows.Forms.Button btnWatchFile;
    private System.Windows.Forms.ListBox lstNotification;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.Timer tmrEditNotify;
    private System.Windows.Forms.OpenFileDialog dlgOpenFile;
    private System.Windows.Forms.FolderBrowserDialog dlgOpenDir;
    private System.Windows.Forms.Button btnLog;
    private System.Windows.Forms.SaveFileDialog dlgSaveFile;
    private System.Windows.Forms.ListBox listBox1;
    private System.Windows.Forms.BindingSource frmNotifierBindingSource;
}

}

1 个答案:

答案 0 :(得分:0)

您当前的代码未编译。 ReadLine应为ReadAllLines

并且没有代码可以设置列表框值,因此列表框值不会更改。

尝试使用此代码:

  private void OnChanged(object sender, FileSystemEventArgs e)
  {
       if (!m_bDirty)
       {
             m_Sb.Remove(0, m_Sb.Length);
             m_Sb.Append(e.FullPath);
             m_Sb.Append(" ");
             m_Sb.Append(e.ChangeType.ToString());
             m_Sb.Append("    ");
             m_Sb.Append(DateTime.Now.ToString());
             m_bDirty = true;
             list = new List<string>(File.ReadAllLines(txtPath));
             bindingList = new BindingList<string>(list);
             listBox1.DataSource = bindingList;
        }
    }

<强>更新

检查完整的代码后,您觉得这段代码(frmNotifier.cs)错了:

  m_bIsWatching = true;

该代码将导致您的FileWatcher事件处理程序未注册。 尝试调试它..