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

标签 delphi logging filestream file-locking

我正在尝试使用 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;

如果有人有任何建议,我们将不胜感激。

最佳答案

尝试使用 Network Share API 关闭文件,即 NetFileEnum 和 NetFileClose 函数。另请参阅a related question

关于当网络丢失时,Delphi 使用 TFilestream 写入网络共享锁定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12084453/

相关文章:

ruby-on-rails - 从脚本/运行程序禁用 Rails 日志记录

java - 自定义ConfigurationFactory结合log4j2中的配置文件

Python日志记录,如何过滤特定的记录器

delphi - 使用delphi从sql查询中解析参数

delphi - 如何仅使油漆盒/位图的一部分无效以优化其性能?

delphi - Delphi错误: Got “untyped” , expected “AnsiString”

c# - 将多个文件流合并到一个文件中?

delphi - DWScript:调用后如何获取结果

Ruby 临时文件与文件

c# - 在 FileStream 弹出响应后删除临时文件