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

C# 使用filewatcher C自动刷新列表框#,c#,file,text,listbox,refresh,C#,File,Text,Listbox,Refresh,好的,我已经做了一段时间了。我有一个程序可以监视一个文件“lab.txt”的更改,当它更改时,我希望它将文件的内容重新加载到显示的列表框中。我可以让它显示,并告诉我何时有变化,但我不能让列表框刷新。任何帮助都会得到报答。现在有很多代码没有被使用,因为我一直在尝试不同的方法,所以请忽略 namespace FileChangeNotifier { public partial class frmNotifier : Form { private StringBuilder m_Sb;

好的,我已经做了一段时间了。我有一个程序可以监视一个文件“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));

    }
} 




}
命名空间文件更改通知程序
{
公共部分类frmNotifier:表单
{
私人建筑商m_Sb;
私人住宅;
private System.IO.FileSystemWatcher m_Watcher;
私人布尔穆比斯威辛;
公共静态字符串txtPath=“E:/lab.txt”;
名单;
绑定列表绑定列表;
公共frmNotifier()
{
初始化组件();
m_Sb=新的StringBuilder();
m_bDirty=false;
m_bisweeting=假;
//BindingSource BindingSource=(BindingSource)listBox1.DataSource;
//List SourceList=(List)bindingSource.List;
list=新列表(File.ReadLines(txtPath));
bindingList=新的bindingList(列表);
listBox1.DataSource=bindingList;
//listBox1.SelectedIndex=-1;
m_bisweeting=真;
btnWatchFile.BackColor=Color.Red;
m_Watcher=new System.IO.FileSystemWatcher();
m_Watcher.Filter=“lab.txt”;
m_Watcher.Path=“E:\\”;
m|u Watcher.NotifyFilter=NotifyFilters.LastAccess | NotifyFilters.LastWrite
|NotifyFilters.FileName | NotifyFilters.DirectoryName;
m_Watcher.Changed+=新文件系统EventHandler(一旦更改);
m_Watcher.Created+=新文件系统EventHandler(一旦更改);
m_Watcher.Deleted+=新文件系统EventHandler(一旦更改);
m_Watcher.rename+=新重命名的EventHandler(OnRename);
m_Watcher.EnableRaisingEvents=true;
}
私有void btnWatchFile_单击(对象发送方,事件参数e)
{
如果(m_)
{
m_bisweeting=假;
m_Watcher.EnableRaisingEvents=false;
m_Watcher.Dispose();
btnWatchFile.BackColor=Color.LightSkyBlue;
btnWatchFile.Text=“开始观看”;
}
其他的
{
m_bisweeting=真;
btnWatchFile.BackColor=Color.Red;
btnWatchFile.Text=“停止观看”;
m_Watcher=new System.IO.FileSystemWatcher();
//如果(rdbDir.Checked)
//
m_Watcher.Filter=“lab.txt”;
m_Watcher.Path=“E:\\”;
//
/*伦敦证券交易所
{
m_Watcher.Filter=txtFile.Text.Substring(txtFile.Text.LastIndexOf('\\')+1);
m_Watcher.Path=txtFile.Text.Substring(0,txtFile.Text.Length-m_Watcher.Filter.Length);
}
如果(chkSubFolder.Checked)
{
m_Watcher.IncludeSubdirectories=true;
}*/
m|u Watcher.NotifyFilter=NotifyFilters.LastAccess | NotifyFilters.LastWrite
|NotifyFilters.FileName | NotifyFilters.DirectoryName;
m_Watcher.Changed+=新文件系统EventHandler(一旦更改);
m_Watcher.Created+=新文件系统EventHandler(一旦更改);
m_Watcher.Deleted+=新文件系统EventHandler(一旦更改);
m_Watcher.rename+=新重命名的EventHandler(OnRename);
m_Watcher.EnableRaisingEvents=true;
}
}
私有void OnChanged(对象发送方、文件系统目标)
{
如果(!m_bDirty)
{
m_Sb.移除(0,m_Sb.长度);
m_Sb.Append(如完整路径);
m_Sb.追加(“”);
m_Sb.Append(例如ChangeType.ToString());
m_Sb.追加(“”);
m_Sb.Append(DateTime.Now.ToString());
m_bDirty=真;
}
}
私有void OnRenamed(对象发送方,RenamedEventArgs e)
{
如果(!m_bDirty)
{
m_Sb.移除(0,m_Sb.长度);
m_Sb.Append(例如OldFullPath);
m_Sb.追加(“”);
m_Sb.Append(例如ChangeType.ToString());
m_Sb.追加(“”);
m_某人附加(“至”);
m_Sb.追加(如姓名);
m_Sb.追加(“”);
m_Sb.Append(DateTime.Now.ToString());
m_bDirty=真;
}            
}
私有void tmrEditNotify_勾选(对象发送方,事件参数e)
{
如果(m_b irty)
{
lstNotification.BeginUpdate();
lstNotification.Items.Add(m_Sb.ToString());
lstNotification.EndUpdate();
m_bDirty=false;
}
}
私有void btnBrowseFile\u单击(对象发送者,事件参数e)
{
}
私有void btnLog_单击(对象发送者,事件参数e)
{
DialogResult resDialog=dlgSaveFile.ShowDialog();
if(resDialog.ToString()=“确定”)
{
FileInfo fi=新的FileInfo(dlgSaveFile.FileName);
StreamWriter sw=fi.CreateText();
foreach(lstNotification.Items中的字符串sItem)
{
西南写入线(sItem);
}
sw.Close();
}
}
公共数据()
{
listBox1.DataSource=null;
bindingList=null;
list=新列表(File.ReadLines(txtPath));
bindingList=新的bindingList(列表);
listBox1.DataSource=bindingList;
}
私有void Execute(对象发送方、事件参数)
{
string task=TaskQue.Pop();
//执行任务;
listBox1.DataSource=TaskQue.GetTasks();
}
私有void AddTask(对象发送方,事件参数e)
{
TaskQue.Push(listBox1.Text);
listBox1.DataSource=TaskQue.GetTasks();
}
私有void txtFile_TextChanged(对象发送方,事件参数e)
{
}
私有void lstNotification\u SelectedIndexChanged(对象发送方,事件参数e)
{
}
 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;
        }
    }
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;
}
  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;
        }
    }
  m_bIsWatching = true;