我正在尝试使用 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;
如果有人有任何建议,将不胜感激。