-1

files was uploaded via FTP,it thows a IO Exception that file was occupied

var watcher = new FileSystemWatcher();
watcher.Created += (sender, e) =>
{
    var lines = File.ReadAllLines(e.FullPath, Encoding.UTF8); //io exception here
};

waiting for your answer,thanks a lot.

Reimu Lyu
  • 31
  • 3
  • try adding a small delay before reading the file in the Created event. Like 50/100 ms – Abhishek Jun 30 '17 at 09:42
  • The problem is that files dont insta-poof into existance, any decent size file takes more than 0ms to arrive. The problem lies in that you cant as easily tell when the upload is completed. The bigger the file the longer it would need. On unix its easier because the file grows as the ftp comes in and you can do a watch on the size and while it still changes leave it alone.. however windows tends to allocate and fill.. – BugFinder Jun 30 '17 at 09:53
  • How about checking file is locked when it's created if file locked then wait for sometime and retry. By this way you can achieve downloading large files. static bool IsFileLocked(FileInfo file) { FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { return true; } finally { if (stream != null) stream.Close(); } return false; } – Sushil Mate Jun 30 '17 at 12:40

2 Answers2

-1

You can use while and try-catch block. Put your file-reading code in while loop and loop until you successfully read file (it means that you passed try block successfully). Or use some delay, like suggested in comments (but this doesn't guarantee, that exception won't occur).

You will exit on two occasions: file successfully read or exception other than IO is thrown. It means you need more sophisticated catch part. You can go more into details with this :)

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
-1

Just add a small delay like:

var watcher = new FileSystemWatcher();
watcher.Created += (sender, e) =>
{
    Thread.Sleep(10);
    var lines = File.ReadAllLines(e.FullPath, Encoding.UTF8); //io exception here
};

Since you have mentioned that the file is big, you can follow the code posted in the following SO Post

Abhishek
  • 2,925
  • 4
  • 34
  • 59
  • yes,small file it works,but file more than 100MB it will throw the same exception……maybe use while and try-catch and Thread.Sleep is the right solution... – Reimu Lyu Jun 30 '17 at 10:09