TFilestream を使用してネットワーク共有 (ローカル) に書き込もうとしています。ネットワーク接続が中断されなければ、すべて正常に機能します。
ただし、ネットワーク ケーブルを抜いてから再接続すると、アクセス制限により、その後ファイル ストリームを開こうとすると失敗します。また、エクスプローラーでファイルを削除することさえできません! TFilestream がファイルをロックしているように見えますが、これを回避する唯一の方法は再起動することです。
私のアプリケーションでは、ファイルに書き込んでいる間ずっとファイルを開いたままにします (これは 1 秒ごとに書き込まれるログ ファイルです)。
失敗する私のコードは以下のとおりです。
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;
誰かにアドバイスがあれば、それはありがたいです。