I am building an windows software using c# to read log (textfile) that is continuously changing (every second )
Following is my code. When I run it how ever, i get an error
An exception of type 'System.IO.IOException' occurred in mscorlib.dll but was not handled in user code.
Additional information: The process cannot access the file 'C:\Users\Steve\Documents\Visual Studio 2015\Projects\iosLogger\IosSysLogger\bin\Debug\syslog.txt' because it is being used by another process.
My logic behind is that i want to build an logger that read the text file everytime there is a change to it. But it seems like it only invokes and loops around ( it crashes anyway) What would my problem be?
string currentPath = System.Environment.CurrentDirectory;
public Form1()
{
InitializeComponent();
string currentPath = System.Environment.CurrentDirectory;
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = currentPath;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
textBox1.BeginInvoke(new Action(() =>
{
string[] fileContents;
fileContents = File.ReadAllLines(currentPath + @"\syslog.txt");
foreach (string line in fileContents)
{
textBox1.AppendText(line + "\n");
}
}));
}