1
Reply

Cross thread error in filewatcher

Nima naqipoor

Nima naqipoor

Mar 6 2010 12:12 PM
6.6k
I have a problem here ;it's a filewatcher programm:
you enter a path in textbox,then go to that path and form example create or delete a folder then I want to log that
event
namespace filewatcherWFA
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}


FileSystemWatcher fsw;

public void WriteLog(string s)
{
// Get the Exact Location of the textFile
string LogFilePath = Directory.GetParent(Application.ExecutablePath).ToString() + @"\Log.txt";

//Create the StremWriter Object with FileName as Constuctor Argument and the Second Parameter is For
Weather Text is Appnded or Not
StreamWriter sw = new StreamWriter(LogFilePath, true);

sw.WriteLine(s);

sw.Close();

textBox2.Text = s+"\t"; //error occures here ((Cross-thread)) !!
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void button1_Click(object sender, EventArgs e)
{

string path=textBox1.Text;
fsw = new FileSystemWatcher(path);
label1.Visible = true;
label1.Text = "path entered !";
fsw.EnableRaisingEvents = true;
fsw.IncludeSubdirectories = true;
fsw.Deleted += new FileSystemEventHandler(fsw_Deleted);
fsw.Created += new FileSystemEventHandler(fsw_Created);
}

void fsw_Created(object sender, FileSystemEventArgs e)
{
WriteLog("created File :" + e.FullPath);
}

void fsw_Deleted(object sender, FileSystemEventArgs e)
{
WriteLog("Deleted File :" + e.FullPath);
}



}
}

but when you are about to delete or create a folder it says::

<<Cross-thread operation not valid: Control 'textBox' accessed from a thread other than the thread it was created 

on.>>

how can I fix that error?


Answers (1)