2013-07-18 3 views
0

Хорошо, я был на этом некоторое время. У меня есть программа, которая отслеживает один файл «lab.txt» для изменений, и когда он изменяется, я хочу, чтобы он загружал содержимое файла в отображаемый список. Я могу заставить его отображать и сообщать мне, когда есть изменения, но я не могу получить список для обновления. любая помощь будет применена. Существует много кода, который не используется сейчас, потому что я пытаюсь использовать разные методы, поэтому, пожалуйста, не обращайте внимания.listbox обновить автоматически с помощью filewatcher C#

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)); 

    } 
} 




} 

EDIT:

Это то, что я не изменился и по-прежнему не идут

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; 
} 

}

+0

Скомпилировано? 'ReadLine' должен быть' ReadAllLines' –

ответ

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; 
     } 
    } 

UPDATE

После проверки вашего полного кода, кажется, что вы имеете неправильно в этом коде (frmNotifier.cs):

m_bIsWatching = true; 

Этот код будет причиной того, что обработчик события FileWatcher не зарегистрирован. Попробуйте отладить его.

+0

Я действительно сделал это, LOL, но не с ReadAllLines. К сожалению, он все еще делает то же самое. Filewatcher видит изменения, но список не обновляется – user2510640

+0

Вы отправляете полный код? Я пробовал свой пост, и он работает нормально ... –

+0

все, кроме этого: 'using System; с использованием System.Collections.Generic; с использованием System.ComponentModel; с использованием System.Data; с использованием System.Drawing; с использованием System.Text; с использованием System.Windows.Forms; с использованием System.IO; с использованием System.Data.Linq; ' – user2510640

Смежные вопросы