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::
<
on.>>
how can I fix that error?
1 Reply
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sam HobbsPosted Mar 6, 2010, 9:11 PM
I got that from the MSDN.
That's easy. Your file watcher is in a thread different from the form, and forms are not thread-safe. So .Net won't let it happen because if it did, you could have an error that would more difficult to diagnose. Instead, it gives the error message that is easy to solve. See: How to: Make Thread-Safe Calls to Windows Forms Controls. The following is written for just one textbox and since you have two textboxex, you need to modify the following accordingly.
In your Form class, add the member:
Then create a method:
Then instead of:
Do: