我試圖使用TFilestream寫入網絡共享(本地)。如果網絡連接不被中斷,它一切正常。使用TFilestream寫入網絡共享的Delphi在網絡丟失時鎖定文件
但是,如果我拔出網線並重新連接,則由於訪問限制,後續嘗試打開文件流失敗。我也無法刪除資源管理器中的文件! 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;
如果任何人有任何意見,我們將不勝感激。
這是真的TFileStream問題?如果是這樣,那麼就使用其他的東西,比如CreateFile。 –