Currently i'm working on an application, that should watch a specific directory for changes (say a new file was created) and then in turn upload the file to Sharepoint. Thatfore i'm using the FileSystemWatcher class which throws an event with the path to the created file, which in turn i use in another method to upload the file. The problem is: While in debug mode in Visual Studio i realized that the first file i create in the watched directory gets uploaded perfectly, even if i drag multiple files into the directory at once all are uploaded, BUT when i do it one file after another i get an exception that the second file is already in use. So i drag File1.txt into the directory, it works, but then, when i drag file2.txt into the directory right after i get a System.IO.IOException while trying to create a filestream to upload to Sharepoint telling me that file2.txt is in use by another process.
The code for the FileSystemWatcher:
public void StartWatcher()
{
FileSystemWatcher fsw = new FileSystemWatcher(this.path);
fsw.IncludeSubdirectories = true;
fsw.EnableRaisingEvents = true;
fsw.Created += new FileSystemEventHandler(CreateFile);
try
{
while (true)
{
fsw.WaitForChanged(WatcherChangeTypes.All);
}
}
catch
{ }
fsw.EnableRaisingEvents = false;
}
The CreateFile() method called by
fsw.Created += new FileSystemEventHandler(CreateFile);
looks like this:
private void CreateFile(object sender, FileSystemEventArgs e)
{
path = String.Format(e.FullPath);
filename = Path.GetFileName(path);
Stream fs = File.OpenRead(@path);
SPAPI spobj = new SPAPI();
spobj.SPUploader(fs, filename);
fs.Close();
}
The exception is thrown at
Stream fs = File.OpenRead(@path);
BUT only when a second file is dragged into the directory after the first one. The strange thing is that not the first file is in use, but the second one that i want to open as a stream. So it's not the stream that is still open and causing the exception. It seems that the second file is in use by the FileSystemWatcher. But why does the first file work just fine but the exception is just thrown when a second file is dragged into the directory?
fsw.WaitForChanged(WatcherChangeTypes.All);- Ditch this. And that abomination of a loop around it including that empty catch.CreateFilenew file created into watched directory. However, you drag and drop file into directory does not mean you could use that file, because file probably still copying into directory. If your file size is standard and you know how much time require for copy/create operation, you can addThread.Sleep()beforepath = String.Format(e.FullPath);Thread.Sleep(100)is not very reliable solution. Try to copy 1GB file to your folder and you'll see how it will fail withThread.Sleep(100).