当网络丢失时,Delphi使用TFilestream写入网络共享会锁定文件

Sim*_*mon 5 delphi logging file-locking filestream

我试图使用TFilestream写入网络共享(本地).如果网络连接没有中断,一切正常.

但是,如果我拉网线然后重新连接,则由于访问限制而导致打开文件流的后续尝试失败.我甚至无法删除资源管理器中的文件!似乎TFilestream锁定文件,解决这个问题的唯一方法是重启.

在我的应用程序中,我在写入文件的整个过程中保持文件打开(这是每秒写一次的日志文件).

我失败的代码如下:

procedure TFileLogger.SetLogFilename(const Value: String);
var line : String;
Created : Boolean;
begin
  if not DirectoryExists(ExtractFilePath(Value)) then //create the dir if it doesnt exist
  begin
       try
         ForceDirectories(ExtractFilePath(Value));
       except
         ErrorMessage(Value); //dont have access to the dir so flag an error
         Exit;
       end;
  end;
  if Value <> FLogFilename then //Either create or open existing
  begin
      Created := False;          
      if Assigned(FStream) then
         FreeandNil(FStream);
      if not FileExists(Value) then   //create the file and write header
      begin
           //now create a new file
           try
              FStream := TFileStream.Create(Value,fmCreate);
              Created := True;
           finally
             FreeAndNil(FStream);
           end;
           if not Created then //an issue with creating the file
           begin
                ErrorMessage(Value);
                Exit;
           end;
           FLogFilename := Value;
           //now open file for writing
           FStream := TFileStream.Create(FLogFilename,fmOpenWrite or fmShareDenyWrite);
           try
              line := FHeader + #13#10;
              FStream.Seek(0,soFromEnd);
              FStream.Write(Line[1], length(Line));
              FSuppress := False;
           except
              ErrorMessage(Value);  
           end;
      end else begin //just open it
           FLogFilename := Value;
           //now open file for writing
           FStream := TFileStream.Create(FLogFilename,fmOpenWrite or fmShareDenyWrite); //This line fails if the network is lost and then reconnected
      end;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

如果有人有任何建议,将不胜感激.

klu*_*udg 7

尝试使用关闭您的文件网络共享API,即NetFileEnum和NetFileClose功能.另见相关问题