您好我正在尝试将文件夹中的文件名列表加载到Stringlist中.我只想添加以.jpg结尾的文件名.当我现在运行它时,我得到访问冲突错误.这是我得到的.
选择目录.
procedure TMainForm.Load1Click(Sender: TObject);
var
DirName: string;
begin
mylist.Free;
myList := TList<TBitmap>.Create;
DirName := 'c:\';
if SelectDirectory(DirName,[sdAllowCreate, sdPerformCreate, sdPrompt],SELDIRHELP)
then;
LoadImages(DirName);
end;
Run Code Online (Sandbox Code Playgroud)
获取文件夹中的totalfiles数
function GetFilesCount(Dir : string; Mask : string) : integer;
var
Path : string;
begin
Result := 0;
for Path in TDirectory.GetFiles(Dir, Mask) do
inc(Result);
end;
Run Code Online (Sandbox Code Playgroud)
从文件夹中获取文件名
function TMainForm.GetFilenames(Path: string ):TStrings;
var
Dest: TStrings;
SR: TSearchRec;
begin
Dest.create;
if FindFirst(Path+'*.*', faAnyFile, SR) = 0 then
repeat
Dest.Add(SR.Name);
until FindNext(SR) <> 0;
FindClose(SR);
Result := Dest;
Dest.Free;
end;
Run Code Online (Sandbox Code Playgroud)
和负载
procedure TMainForm.LoadImages(const Dir: string);
const
FIRST_IMAGE = 0;
var
iFile : Integer;
CurFileName: string;
FoundFile : boolean;
FileNameTemplate : string;
FileNames : Tstrings;
begin
FileNames.Create;
FileNameTemplate := IncludeTrailingPathDelimiter(Dir) + '*.jpg'; FileNames:=GetFileNames(FileNameTemplate);
try
ifile := 0;
repeat
CurFileName := FileNames.Names[ifile];
showmessage(Curfilename);
if FoundFile then
begin
end;
Inc(iFile);
end;
until not FoundFile;
end;
Run Code Online (Sandbox Code Playgroud)
问题在这里(你实际上有两个问题) - 实际上,你的代码中有两次相同的问题:
Dest.Create; // In GetFileNames
FileNames.Create; // In LoadImages
Run Code Online (Sandbox Code Playgroud)
首先,TStrings是一个抽象类.你不能创建它的实例; 它是其他更具体的类的基础TStringList.改为创建其中一个具体类.
其次,您必须创建TStringList并存储对它的引用.
FileNames := TStringList.Create;
Run Code Online (Sandbox Code Playgroud)
更好的方法是创建stringlist并将其传递给函数或过程,因为返回时需要结果.我将为你快速通过其中一个:
function TMainForm.GetFilenames(const Path: string; const FileList: TStringList ): Boolean;
var
SR: TSearchRec;
begin
Assert(Assigned(FileList)); // Make sure it was created and passed in
FileList.Clear; // Remove any previous names
if FindFirst(Path+'*.*', faAnyFile, SR) = 0 then
repeat
FileList.Add(SR.Name);
until FindNext(SR) <> 0;
FindClose(SR);
Result := FileList.Count > 0; // Return true if we have found any files
end;
Run Code Online (Sandbox Code Playgroud)
像这样称呼它:
FileNames := TStringList.Create;
try
if GetFileNames(PathToFolder, FileNames) then
begin
// Process files here
for i := 0 to FileNames.Count - 1 do
begin
CurrFile := FileNames[i];
// Use the file here from CurrFile
end;
end;
finally
FileNames.Free;
end;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2751 次 |
| 最近记录: |