Delphi ini file reading - delphi

Im stuck and asking for your help te get a solution for reading my ini file back and placing that in my memo1 form with a button.
This is in my text file:
[Filename]
Work Time=03-10-2018 15:11
Here is some of the code im working with.
var
aWorkTime: string;
procedure TForm1.button2(Sender: TObject):
begin
Memo1.Lines.Clear;
IniFile := TIniFile.Create(GetCurrentDir+'\Filename.ini');
try
aWorkTime := IniFile.ReadString('Filename', 'Work Time', <'none'>);
finally
IniFile.Free;
end;
end
I hope that this is enough information if not please tell me what you are missing from me

Your use of GetCurrentDir is problematic. The current dir may change and doesn't have to be the same directory as where your .exe file resides. Rather use ExtractFilePath(Application.ExeName)
Also, instead of reading the items one by one, to read the entire .ini file into your memo, do something like:
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo1.Lines.LoadFromFile(ExtractFilePath(Application.ExeName) + 'FileName.ini');
end;
If you only need the work time, then your code is almost there:
var
aWorkTime: string;
IniFile: TIniFile;
begin
Memo1.Lines.Clear;
IniFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'FileName.ini');
try
aWorkTime := IniFile.ReadString('Filename', 'Work Time', '<none>');
Memo1.Lines.Add('Work Time=' + aWorkTime);
finally
IniFile.Free;
end;
end;

Related

Reading Word-file (*.dot) from program resources

Have a set of Word-templates (files *.dot) and a little program, which create new files base on that templates. It's works fine, but the goal is to make all in one exe-file.
I see the solution is to move templates files into program resources. But I don't know, how then I will read them from resources. Tell me, please, how to do this.
Maybe you can advise me another solution.
Now, my code is:
procedure TfmMain.CreateDocument0;
var
TempleateFileName: string;
WordApp, Document: OleVariant;
procedure FillBookmark(BookmarkName, bText: string);
var
Range: OleVariant;
begin
if Document.Bookmarks.Exists(BookmarkName) then
begin
Range := Document.Bookmarks.Item(BookmarkName).Range;
Range.Text := bText;
end;
end;
begin
TempleateFileName := ExtractFilePath(Application.ExeName)+'Templates\0.dot';
try
WordApp := GetActiveOleObject('Word.Application');
except
try
WordApp := CreateOleObject('Word.Application');
except
on E: Exception do
begin
MessageBox(Self.Handle, PChar(E.Message), PChar(fmMain.Caption), MB_OK+MB_ICONERROR);
Exit;
end;
end;
end;
try
Document := WordApp.Documents.Add(TempleateFileName, False);
FillBookmark('ObjectType', edt0ObjectType.Text);
...
WordApp.Visible := True;
WordApp.Activate;
finally
WordApp := Unassigned;
end;
end;
That is, I should change this line:
Document := WordApp.Documents.Add(TempleateFileName, False);
Read not from file, but from program resource.
Word cannot open documents from memory. Not only does it not have such a feature, you must also bear in mind that Word executes in a separate process. It cannot see the memory in your process, even if it were able to open documents from memory.
If you do put the documents into linked resources then you will need to extract them to file before asking Word to open them.

Delphi - automatically Loads the Last Used of .INI File [duplicate]

I modified the MasterMan82's TIniFile code to read and write multi values from & to TEdit/TComboBox and TMemo.
Forgive my vague questions, my english is not good.
So, what I mean is:
I have a couple of .INI files, A.ini, B.ini, C.ini ....and so on. I just store A.ini as a variable in the code. It is not possible to put all the file names in the code.
When I opened A.ini, make some changes, click SAVE to save any changes made, and success!. Of course, because A.ini has been defined in the code.
However, when I open the file B.ini or C.ini or D.ini...making the change, and save, reopen the file, but all changes in the file is gone or not saved, of course, because only the A.ini was defined in the code.
So, my goal is how to keep or records all file revisions ?
Below is the code.
......
uses
Windows, Messages, SysUtils, Variants, Classes,
Graphics, Controls, Forms, IniFiles, Dialogs;
......
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
I, LinesCount: Integer;
Read : TIniFile;
begin
Read := TINIFile.Create(ExtractFilePath(Application.EXEName)+ 'A.ini');
// Read := TIniFile.Create(ChangeFileExt(Application.Exename,'A.ini'));
Try
Proxy.Text := Read.ReadString('SETTING','Proxy','');
Port.Text := Read.ReadString('SETTING','Port','');
Route.Checked:= Read.ReadBool('SETTING','Route',False);
// TO READ MEMO LINES
LinesCount := Read.ReadInteger('MEMO', 'Lines Count', 0);
for I := 0 to LinesCount-1 do
Memo1.Lines.Insert(I, Read.ReadString('MEMO', 'Item'+IntToStr(I), ''));
Finally
Read.Free;
end;
end;
procedure TForm1.SaveClick(Sender: TObject);
var
I, LinesCount: Integer;
ToSave : TIniFile;
begin
ToSave := TINIFile.Create(ExtractFilePath(Application.EXEName)+ 'A.ini');
Try
ToSave.WriteString('SETTING','Proxy',Proxy.Text);
ToSave.WriteString('SETTING','Port',Port.Text);
ToSave.WriteBool('SETTING','Route',Route.Checked);
// TO SAVE MEMO LINES
LinesCount := Memo1.Lines.Count;
ToSave.WriteInteger('MEMO', 'Lines Count', LinesCount);
for I := 0 to LinesCount-1 do
ToSave.WriteString('MEMO', 'Item'+IntToStr(I), Memo1.Lines[I]);
Finally
ToSave.Free;
end;
end;
procedure TForm1.OpenClick(Sender: TObject);
var
I, LinesCount: Integer;
OpenFile : TIniFile;
begin
OpenDialog.Filter:='Ini File (.ini)|*.ini';
if OpenDialog.Execute then begin
Memo1.Clear;
OpenFile := TINIFile.Create(OpenDialog.FileName);
Try
Proxy.Text := OpenFile.ReadString('SETTING','Proxy','');
Port.Text := OpenFile.ReadString('SETTING','Port','');
Route.Checked:= OpenFile.ReadBool('SETTING','Route',False);
// TO READ MEMO LINES
LinesCount := OpenFile.ReadInteger('MEMO', 'Lines Count', 0);
for I := 0 to LinesCount-1 do
Memo1.Lines.Insert(I, OpenFile.ReadString('MEMO', 'Item'+IntToStr(I), ''));
Finally
OpenFile.Free;
end;
end;
end;
When you open an ini file, store the filename in a variable as explained in many comments.
Example, (FCurrentIniFilename: String; is a private variable in TForm1):
In the FormCreate event:
FCurrentIniFilename := ExtractFilePath(Application.EXEName)+ 'A.ini';
Read := TINIFile.Create(FCurrentIniFilename);
...
In the OpenFile event:
if OpenDialog.Execute then begin
FCurrentIniFilename := OpenDialog.Filename;
Open := TINIFile.Create(FCurrentIniFileName);
try
...
finally
Open.Free;
end;
end;
When you are saving the information:
ToSave := TINIFile.Create(FCurrentIniFilename);
You're expecting there to be magic where none exists. If you want to save to the same file you opened, then store the chosen name in a variable when you open it, and then use that variable when you save, too.
Likewise, if you want to remember the name from one run to the next, then you need to store the name in persistent storage (like the registry or an INI file), and then read that name when your program starts next time.
It's not difficult to get what you've requested, but you'll have to write some code for it.

Delphi 7 - Save to a Specific .INI Files Name

I modified the MasterMan82's TIniFile code to read and write multi values from & to TEdit/TComboBox and TMemo.
Forgive my vague questions, my english is not good.
So, what I mean is:
I have a couple of .INI files, A.ini, B.ini, C.ini ....and so on. I just store A.ini as a variable in the code. It is not possible to put all the file names in the code.
When I opened A.ini, make some changes, click SAVE to save any changes made, and success!. Of course, because A.ini has been defined in the code.
However, when I open the file B.ini or C.ini or D.ini...making the change, and save, reopen the file, but all changes in the file is gone or not saved, of course, because only the A.ini was defined in the code.
So, my goal is how to keep or records all file revisions ?
Below is the code.
......
uses
Windows, Messages, SysUtils, Variants, Classes,
Graphics, Controls, Forms, IniFiles, Dialogs;
......
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
I, LinesCount: Integer;
Read : TIniFile;
begin
Read := TINIFile.Create(ExtractFilePath(Application.EXEName)+ 'A.ini');
// Read := TIniFile.Create(ChangeFileExt(Application.Exename,'A.ini'));
Try
Proxy.Text := Read.ReadString('SETTING','Proxy','');
Port.Text := Read.ReadString('SETTING','Port','');
Route.Checked:= Read.ReadBool('SETTING','Route',False);
// TO READ MEMO LINES
LinesCount := Read.ReadInteger('MEMO', 'Lines Count', 0);
for I := 0 to LinesCount-1 do
Memo1.Lines.Insert(I, Read.ReadString('MEMO', 'Item'+IntToStr(I), ''));
Finally
Read.Free;
end;
end;
procedure TForm1.SaveClick(Sender: TObject);
var
I, LinesCount: Integer;
ToSave : TIniFile;
begin
ToSave := TINIFile.Create(ExtractFilePath(Application.EXEName)+ 'A.ini');
Try
ToSave.WriteString('SETTING','Proxy',Proxy.Text);
ToSave.WriteString('SETTING','Port',Port.Text);
ToSave.WriteBool('SETTING','Route',Route.Checked);
// TO SAVE MEMO LINES
LinesCount := Memo1.Lines.Count;
ToSave.WriteInteger('MEMO', 'Lines Count', LinesCount);
for I := 0 to LinesCount-1 do
ToSave.WriteString('MEMO', 'Item'+IntToStr(I), Memo1.Lines[I]);
Finally
ToSave.Free;
end;
end;
procedure TForm1.OpenClick(Sender: TObject);
var
I, LinesCount: Integer;
OpenFile : TIniFile;
begin
OpenDialog.Filter:='Ini File (.ini)|*.ini';
if OpenDialog.Execute then begin
Memo1.Clear;
OpenFile := TINIFile.Create(OpenDialog.FileName);
Try
Proxy.Text := OpenFile.ReadString('SETTING','Proxy','');
Port.Text := OpenFile.ReadString('SETTING','Port','');
Route.Checked:= OpenFile.ReadBool('SETTING','Route',False);
// TO READ MEMO LINES
LinesCount := OpenFile.ReadInteger('MEMO', 'Lines Count', 0);
for I := 0 to LinesCount-1 do
Memo1.Lines.Insert(I, OpenFile.ReadString('MEMO', 'Item'+IntToStr(I), ''));
Finally
OpenFile.Free;
end;
end;
end;
When you open an ini file, store the filename in a variable as explained in many comments.
Example, (FCurrentIniFilename: String; is a private variable in TForm1):
In the FormCreate event:
FCurrentIniFilename := ExtractFilePath(Application.EXEName)+ 'A.ini';
Read := TINIFile.Create(FCurrentIniFilename);
...
In the OpenFile event:
if OpenDialog.Execute then begin
FCurrentIniFilename := OpenDialog.Filename;
Open := TINIFile.Create(FCurrentIniFileName);
try
...
finally
Open.Free;
end;
end;
When you are saving the information:
ToSave := TINIFile.Create(FCurrentIniFilename);
You're expecting there to be magic where none exists. If you want to save to the same file you opened, then store the chosen name in a variable when you open it, and then use that variable when you save, too.
Likewise, if you want to remember the name from one run to the next, then you need to store the name in persistent storage (like the registry or an INI file), and then read that name when your program starts next time.
It's not difficult to get what you've requested, but you'll have to write some code for it.

Reading value without using sections

How do I read value from INI file without using sections?
So instead of normal file:
[section]
name=value
it would result in this:
name=value
I wouldn't call it an INI file, then. Anyhow, for this the TStringList class fits perfectly.
Consider the file animals.txt:
dog=Sally
rat=Fiona
cat=Linus
And consider this code:
procedure TForm1.Button1Click(Sender: TObject);
begin
with TStringList.Create do
try
LoadFromFile('C:\Users\Andreas Rejbrand\Desktop\animals.txt');
ShowMessage(Values['dog']);
finally
Free;
end;
end;
There's a nice tutorial over here. For example, if iniFile is an instance of TIniFile, you can call the iniFile.ReadString method with an empty section specifier.
This is a late answer but here is some code I wrote for my project:
function GetPropertyValue(aFile, Key: string): string;
var
properties: TStringList;
begin
properties := TStringList.Create;
try
properties.LoadFromFile(aFile);
Result := properties.Values[key];
finally
properties.free;
end;
end;
procedure SetPropertyValue(aFile, Key, Value: string);
var
I: Integer;
properties: TStringList;
found: Boolean;
begin
found := False;
properties := TStringList.Create;
try
properties.LoadFromFile(aFile);
for I := 0 to properties.Count -1 do
begin
if properties.Names[I] = Key then
begin
properties[I] := Key + '=' + Value;
found := True;
Break
end;
end;
if not found then
begin
properties.Add(Key + '=' + Value);
end;
finally
properties.SaveToFile(aFile);
properties.free;
end;
end;
I think the question really needs more information. Often people will ask questions relating to what they think they need to do instead of asking questions related to what they are actually trying to accomplish.
Why do you need to do this instead of using the normal methods of reading the ini entries?
If these are existing ini files, then you should use the Tinifile.ReadSections to read the section names into a stringlist and then iterate through that list using Tinifile.ReadSectionValues to read all the section name/values pairs.
Are you reading existing INI files, or reading and writing your own files?
If these are your own files, then Andreas has a good answer above.

Embed Excel file in Delphi 5

I'm trying embed an Excel file into my Delphi 5 application, so I can avoid my users just deleting the file accidentally.
Using the embedded file, I create it on disk with a Save dialog, and then open it with the Excel := CreateOleObject('Excel.Application'); method. I've seen examples on how to load a resource, using THandles, but I don't seem to get it working with Excel.WorkBooks.Open(EmbeddedExcelFile);.
Have you had to do something like this before? How would you do it?
Thanks!
You have to include the file as a resource. Say you have a blah.xls
Create a blah.rc file with the following content
blah RCDATA blah.xls
compile it with the resource compiler into blah.res
embed the RES file within the executable
{$R 'blah.res'}
in your application code, extract the file and run it with this code
procedure ExtractAndRun(resourceID:string; resourceFn:string);
var
resourceStream: TResourceStream;
fileStream: TFileStream;
tempPath: string;
fullFileName: string;
begin
tempPath:=GetTempDir;
FullFilename:=TempPath+'\'+resourceFN;
if not FileExists(FullFilename) then
begin
resourceStream := TResourceStream.Create(hInstance, resourceID, RT_RCDATA);
try
fileStream := TFileStream.Create(FullFilename, fmCreate);
try
fileStream.CopyFrom(resourceStream, 0);
finally
fileStream.Free;
end;
finally
resourceStream.Free;
end;
end;
ShellExecute(0,'open', pchar(FullFilename), nil, nil, SW_SHOWNORMAL);
end;
you'll have to add ShellApi in your uses clause
maybe you'll need this GetTempDir function
function GetTempDir: string;
var
Buffer: array[0..MAX_PATH] of char;
begin
GetTempPath(SizeOf(Buffer) - 1, Buffer);
result := StrPas(Buffer);
end;
invoke the function like this
extractAndRun('blah','blah.xls');
I am pretty sure it will not work. You have to save the file in a temp folder, alter it and and then do whatever you want.

Resources