簡體   English   中英

使用Filewatcher C#自動刷新列表框

[英]listbox refresh automatically using filewatcher C#

好吧,我已經有一段時間了。 我有一個程序監視一個文件“ 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;
}

}

您當前的代碼未編譯。 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事件處理程序未注冊。 嘗試調試它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM