title: Delphi: Why do I sometimes get an I/O Error 103 with this code?
body: <p>In several of my apps I have code similar to the following:</p>
  
  <pre><code>if ForceDirectories(ExtractFilePath(lLogName)) then
    begin
      AssignFile(lLog, lLogName);
      try
        if FileExists(lLogName) then
          Append(lLog)
        else
          Rewrite(lLog);
        Writeln(lLog, lLogLine);
      finally
        {$I-}CloseFile(lLog);{$I+}
      end;
    end;
  </code></pre>
  
  <p>In one application, the first time I try to execute this I consistently get an I/O Error 103 exception on the line with the Append statement (the file does exist prior to calling this). All subsequent attempts at the operation will work fine however - until I restart the app.</p>
  
  <p>All the docs I found about this error so far indicated that this would either be caused by calling <code>CloseFile</code> without prior <code>Reset</code> or <code>Rewrite</code> (<code>Append</code> typically isn't mentioned) or if the file was in use by another process. As the exception occurs before the call to <code>CloseFile</code> it obviously couldn't be the former.</p>
  
  <p>I already tried inserting a <code>Reset</code> right after the <code>AssignFile</code> for good measure but then I get the exception on that line.</p>
  
  <p>There is also no other application overtly accessing that file. I say "overtly" because I do have a slight suspicion that anti-virus (TrendMicro in my case) might be the cuplrit here (so maybe the file <strong>is</strong> in use). If that was indeed the problem, what would be the best way around it? Hard-coding an automatic retry does not really feel like a clean solution to me...</p>
  
  <hr>
  
  <p>Another case where I sometimes get the 103 error is this code, which I use to create an empty file (or more often to empty an existing file):</p>
  
  <pre><code>AssignFile(lFile, AFileName);
  try
    Rewrite(lFile);
  finally
    CloseFile(lFile);
  end;
  </code></pre>
  
  <p>In this case it's much harder to reproduce. It happens a lot less often. Most of the time this seems to happen on the first run after I recompiled the application. Could this again be the anti-virus getting in the way? I have only ever seen this happen on my development machine and never gotten a report from a customer. As with the first scenario this only ever happens once per application session (if at all). Subsequent attempts are always successful.</p>
  
  <p>Any suggestions for a different, potentially more fail-safe approach to creating empty files or emptying existing ones?</p>