问题
I'm new to Delphi and i'm a french user so sorry for my bad english...
So it is possible to create a file written in TMemo?
test.txt
dir1/dir2/text.txt
dir3/
My TMemo there are 3 lines, so I would like to take the first line and create the file test.txt in the current directory ..
2nd line: create a folder
3rd line: create a folder again+files.txt
etc ...
I think to use mkdir or ForceDirectories to create Directory and files? etc...
So my conclusion was to automate it.
You can help me please?
a small image so you can see:
回答1:
With Program and on ButtonClick event If I have understood the question correctly, this will
- Create an empty text file in the application directory with the filename as per Memo Line 1
- Create Folders as per Memo Line 2 and in the "base directory" per the edit
- Create a Folder and empty TextFile as per Memo Line 3 again in the "base directory"
procedure TForm1.Button1Click(Sender: TObject);
var
Path: String;
F: TextFile;
begin
// Create File in current directory
Path := ExtractFilePath(ParamStr(0)) + Memo1.Lines.Strings[0];
if not FileExists(Path) then
begin
AssignFile(F, Path);
Rewrite(F);
//Writeln(F, 'text to write to file');
CloseFile(F);
end;
// Create Directories
Path := IncludeTrailingPathDelimiter(edPath.Text) + Memo1.Lines.Strings[1];
if not DirectoryExists(Path) then
ForceDirectories(Path);
// Create Directory and File
Path := IncludeTrailingPathDelimiter(edPath.Text) + Memo1.Lines.Strings[2];
if not DirectoryExists(ExtractFilePath(Path)) then
ForceDirectories(ExtractFilePath(Path));
if not FileExists(Path) then
begin
AssignFile(F, Path);
Rewrite(F);
//Writeln(F, 'text to write to file');
CloseFile(F);
end;
end;
Obviously needs significantly more error checking determining if paths valid and files / directories created etc...
回答2:
Edit: code in browser so have no idea if it works but really is a simple thing to do.
You should only use a TMemo if you want to display the data before you save it, because the task of a visual control is to display something. But if you only want to use the Items propery of the TMemo for collecting strings and then save them to file you should use a TStringList instead:
var
i: Integer;
sl: TStringList;
begin
sl := TStringList.Create;
try
for i := 0 to Memo1.Lines.Count-1 do
sl.Add(Memo1.Lines[i]);
sl.SaveToFile(sl[1]);
finally
sl.free;
end;
end;
You may also like this thread: http://www.tek-tips.com/viewthread.cfm?qid=678231
EDIT2:
Memo1.Lines.SaveToFile(edit1.text + Memo1.Lines[0]);
Provided that Edit Control is named Edit1 and has your base path and first line of the TMemo has the file name. The other bit you need is an Event
and by that I mean if you doubleclick your TMemo instance it will be the event that will start the cascade for saving the file.
As you see it is very easy and there are other ways such as SaveDialog that can make it much easier still. but hope this answers your question.
来源:https://stackoverflow.com/questions/13003927/memo-and-create-file-and-folder