gpt4 book ai didi

Delphi TStreamReader - 如何以共享模式阅读?

转载 作者:行者123 更新时间:2023-12-01 19:40:13 25 4
gpt4 key购买 nike

我在 Delphi Tokyo 中编写了一个例程,它接受多个文件(例如 CSV)并将它们合并在一起,让用户可以选择忽略除第一个文件之外的所有文件的第一行(因为 CSV 文件通常有标题行)/列名称行,合并文件时,我只想要标题的一份副本)。我遇到的问题是,即使我只读取各种输入文件,如果该文件在另一个进程(特别是 Excel)中打开,我的应用程序会给出错误:“无法打开文件。该进程无法访问该文件,因为它正在被另一个进程使用。”

我正在使用 TStreamReader。我如何告诉 TStreamReader 它应该以只读方式打开文件...并继续,即使文件在其他地方打开?

代码如下:

procedure glib_MergeTextFiles(const InFileNames: array of string; const OutFileName: string;
HasHeader: Boolean = True;
KeepHeader: Boolean = True);
var
I: Integer;
InStream: TStreamReader;
OutStream: TStreamWriter;
Line: string;
IsFirstLine: Boolean;
begin
// Create our output stream
OutStream := TStreamWriter.Create(OutFileName, False, TEncoding.UTF8);
try
for I := 0 to high(InFileNames) do
begin
InStream := TStreamReader.Create(InFileNames[I], TEncoding.UTF8);
IsFirstLine := True;
try
while not InStream.EndOfStream do
begin
Line := InStream.ReadLine;

if IsFirstLine then { First Line }
begin
if HasHeader = False then
begin
OutStream.WriteLine(Line);
end
else
begin
// Is First Line, Has Header
if I = 0 then {is first file}
OutStream.WriteLine(Line);
end;
end
else
begin
OutStream.WriteLine(Line);
end;

IsFirstLine := False;
end;

finally
InStream.Free;
end;

end;
finally
OutStream.Free;
end;
end;

最佳答案

问题出在共享模式上。默认情况下,流读取器创建一个仅供读取的文件流,但未指定共享模式,因此它会打开文件以进行独占访问。但是,要打开已在其他地方打开的文件进行读取,该文件必须先前已使用 FILE_SHARE_READ 打开以共享读取访问权限。标志:

FILE_SHARE_READ
0x00000001

Enables subsequent open operations on a file or device to request read access.

Otherwise, other processes cannot open the file or device if they request read access.

If this flag is not specified, but the file or device has been opened for read access, the function fails.

您可以将自己的文件流传递给流读取器,以您喜欢的模式打开:

var
I: Integer;
FileStream: TFileStream;
InStream: TStreamReader;
..
begin
...
FileStream := TFileStream.Create(InFileNames[I], fmOpenRead or fmShareDenyNone);
try
InStream := TStreamReader.Create(FileStream, TEncoding.UTF8);
try
..

同样,这需要 Excel 在打开文件时执行相同的操作,但通过我的简单测试,看起来确实如此。

关于Delphi TStreamReader - 如何以共享模式阅读?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53819888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com