// Replaces a string in a file with new string.
// Ersetzt eine Zeichenkette in einer Datei mit einer anderen Zeichenkette.
procedure TForm1.Button1Click(Sender: TObject);
var
f: file;
l: Longint;
FileName, oldstring, newstring, s: string;
begin
oldstring := 'old string';
newstring := 'new string';
FileName := 'c:\YourFileName.xyz';
s := oldstring;
AssignFile(f, FileName);
Reset(f, 1);
for l := 0 to FileSize(f) - Length(oldstring) - 1 do
begin
Application.ProcessMessages;
Seek(f, l);
BlockRead(f, oldstring[1], Length(oldstring));
if oldstring = s then
begin
Seek(f, l);
BlockWrite(f, newstring[1], Length(newstring));
ShowMessage('String successfully replaced!');
end;
Application.ProcessMessages;
end;
CloseFile(f);
end;
uses
Shellapi;
function GetLongFileName(const FileName: string): string;
var
SHFileInfo: TSHFileInfo;
begin
if SHGetFileInfo(PChar(FileName),
0,
SHFileInfo,
SizeOf(SHFileInfo),
SHGFI_DISPLAYNAME) <> 0 then
Result := string(SHFileInfo.szDisplayName)
else
Result := FileName;
end;
// Example:
procedure TForm1.Button1Click(Sender: TObject);
begin
Caption := GetLongFileName('C:\Program Files\Delphi6\Lib\BK_STR~1.DPK');
// --> BK_StringGrid.dpk
end;
// For > Delphi 4 you can use the ExpandFileName() function
// ExpandFileName converts the relative file name into a fully qualified path name.
function SetFileDateTime(FileName: string; NewDateTime: TDateTime): Boolean;
var
FileHandle: Integer;
FileTime: TFileTime;
LFT: TFileTime;
LST: TSystemTime;
begin
Result := False;
try
DecodeDate(NewDateTime, LST.wYear, LST.wMonth, LST.wDay);
DecodeTime(NewDateTime, LST.wHour, LST.wMinute, LST.wSecond, LST.wMilliSeconds);
if SystemTimeToFileTime(LST, LFT) then
begin
if LocalFileTimeToFileTime(LFT, FileTime) then
begin
FileHandle := FileOpen(FileName, fmOpenReadWrite or
fmShareExclusive);
if SetFileTime(FileHandle, nil, nil, @FileTime) then
Result := True;
end;
end;
finally
FileClose(FileHandle);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
if SetFileDateTime(OpenDialog1.FileName, now) then
ShowMessage('Date set to now !');
end;
// Create a new text file and write some text into it
procedure NewTxt;
var
f: Textfile;
begin
AssignFile(f, 'c:\ek.txt'); {Assigns the Filename}
ReWrite(f); {Create a new file named ek.txt}
Writeln(f, 'You have written text into a .txt file');
Closefile(f); {Closes file F}
end;
// Open existing text file and append some text
procedure OpenTxt;
var
F: Textfile;
begin
AssignFile(f, 'c:\ek.txt'); {Assigns the Filename}
Append(f); {Opens the file for editing}
Writeln(f, 'You have written text into a .txt file');
Closefile(f); {Closes file F}
end;
// Open existing text file and show first line
procedure ReadTxt;
var
F: Textfile;
str: string;
begin
AssignFile(f, 'c:\ek.txt'); {Assigns the Filename}
Reset(f); {Opens the file for reading}
Readln(f, str);
ShowMessage('1. line of textfile:' + str);
Closefile(f); {Closes file F}
end;
{
This code displays the application/file "Open With" dialog
Passing the full file path and name as a parameter will cause the
dialog to display the line "Click the program you want to use to open
the file 'filename'".
}
uses
ShellApi;
procedure OpenWith(FileName: string);
begin
ShellExecute(Application.Handle, 'open', PChar('rundll32.exe'),
PChar('shell32.dll,OpenAs_RunDLL ' + FileName), nil, SW_SHOWNORMAL);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if Opendialog1.Execute then
OpenWith(Opendialog1.FileName);
end;
function Get_File_Size1(sFileToExamine: string; bInKBytes: Boolean): string;
{
for some reason both methods of finding file size return
a filesize that is slightly larger than what Windows File
Explorer reports
}
var
FileHandle: THandle;
FileSize: LongWord;
d1: Double;
i1: Int64;
begin
//a- Get file size
FileHandle := CreateFile(PChar(sFileToExamine),
GENERIC_READ,
0, {exclusive}
nil, {security}
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
FileSize := GetFileSize(FileHandle, nil);
Result := IntToStr(FileSize);
CloseHandle(FileHandle);
//a- optionally report back in Kbytes
if bInKbytes = True then
begin
if Length(Result) > 3 then
begin
Insert('.', Result, Length(Result) - 2);
d1 := StrToFloat(Result);
Result := IntToStr(round(d1)) + 'KB';
end
else
Result := '1KB';
end;
end;
{******************************************************************************
Thanks to Advanced Delphi Systems here's another method which works just as
well returning the same results
*******************************************************************************}
function Get_File_Size2(sFileToExamine: string; bInKBytes: Boolean): string;
var
SearchRec: TSearchRec;
sgPath: string;
inRetval, I1: Integer;
begin
sgPath := ExpandFileName(sFileToExamine);
try
inRetval := FindFirst(ExpandFileName(sFileToExamine), faAnyFile, SearchRec);
if inRetval = 0 then
I1 := SearchRec.Size
else
I1 := -1;
finally
SysUtils.FindClose(SearchRec);
end;
Result := IntToStr(I1);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
label1.Caption := Get_File_Size(Opendialog1.FileName, True);
end;
{*******************************************************************************}
function Get_File_Size3(const FileName: string): TULargeInteger;
// by nico
var
Find: THandle;
Data: TWin32FindData;
begin
Result.QuadPart := -1;
Find := FindFirstFile(PChar(FileName), Data);
if (Find <> INVALID_HANDLE_VALUE) then
begin
Result.LowPart := Data.nFileSizeLow;
Result.HighPart := Data.nFileSizeHigh;
Windows.FindClose(Find);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if (OpenDialog1.Execute) then
ShowMessage(IntToStr(Get_File_Size3(OpenDialog1.FileName).QuadPart));
end;
{*******************************************************************************}
function Get_File_Size4(const S: string): Int64;
var
FD: TWin32FindData;
FH: THandle;
begin
FH := FindFirstFile(PChar(S), FD);
if FH = INVALID_HANDLE_VALUE then Result := 0
else
try
Result := FD.nFileSizeHigh;
Result := Result shl 32;
Result := Result + FD.nFileSizeLow;
finally
CloseHandle(FH);
end;
end;
{
An INI file stores information in logical groupings, called “sections.”
Within each section, actual data values are stored in named keys.
[Section_Name]
Key_Name1=Value1
Key_Name2=Value2
}
uses
IniFiles;
// Write values to a INI file
procedure TForm1.Button1Click(Sender: TObject);
var
ini: TIniFile;
begin
// Create INI Object and open or create file test.ini
ini := TIniFile.Create('c:\MyIni.ini');
try
// Write a string value to the INI file.
ini.WriteString('Section_Name', 'Key_Name', 'String Value');
// Write a integer value to the INI file.
ini.WriteInteger('Section_Name', 'Key_Name', 2002);
// Write a boolean value to the INI file.
ini.WriteBool('Section_Name', 'Key_Name', True);
finally
ini.Free;
end;
end;
// Read values from an INI file
procedure TForm1.Button2Click(Sender: TObject);
var
ini: TIniFile;
res: string;
begin
// Create INI Object and open or create file test.ini
ini := TIniFile.Create('c:\MyIni.ini');
try
res := ini.ReadString('Section_Name', 'Key_Name', 'default value');
MessageDlg('Value of Section: ' + res, mtInformation, [mbOK], 0);
finally
ini.Free;
end;
end;
// Read all sections
procedure TForm1.Button3Click(Sender: TObject);
var
ini: TIniFile;
begin
ListBox1.Clear;
ini := TIniFile.Create('MyIni.ini');
try
ini.ReadSections(listBox1.Items);
finally
ini.Free;
end;
end;
// Read a section
procedure TForm1.Button4Click(Sender: TObject);
var
ini: TIniFile;
begin
ini: = TIniFile.Create('WIN.INI');
try
ini.ReadSection('Desktop', ListBox1.Items);
finally
ini.Free;
end;
end;
// Read section values
procedure TForm1.Button5Click(Sender: TObject);
var
ini: TIniFile;
begin
ini := TIniFile.Create('WIN.INI');
try
ini.ReadSectionValues('Desktop', ListBox1.Items);
finally
ini.Free;
end;
end;
// Erase a section
procedure TForm1.Button6Click(Sender: TObject);
var
ini: TIniFile;
begin
ini := TIniFile.Create('MyIni.ini');
try
ini.EraseSection('My_Section');
finally
ini.Free;
end;
end;
uses
ShellApi;
function CopyDir(const fromDir, toDir: string): Boolean;
var
fos: TSHFileOpStruct;
begin
ZeroMemory(@fos, SizeOf(fos));
with fos do
begin
wFunc := FO_COPY;
fFlags := FOF_FILESONLY;
pFrom := PChar(fromDir + #0);
pTo := PChar(toDir)
end;
Result := (0 = ShFileOperation(fos));
end;
function MoveDir(const fromDir, toDir: string): Boolean;
var
fos: TSHFileOpStruct;
begin
ZeroMemory(@fos, SizeOf(fos));
with fos do
begin
wFunc := FO_MOVE;
fFlags := FOF_FILESONLY;
pFrom := PChar(fromDir + #0);
pTo := PChar(toDir)
end;
Result := (0 = ShFileOperation(fos));
end;
function DelDir(dir: string): Boolean;
var
fos: TSHFileOpStruct;
begin
ZeroMemory(@fos, SizeOf(fos));
with fos do
begin
wFunc := FO_DELETE;
fFlags := FOF_SILENT or FOF_NOCONFIRMATION;
pFrom := PChar(dir + #0);
end;
Result := (0 = ShFileOperation(fos));
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if cCopyDir('d:\download', 'e:\') = True then
ShowMessage('Directory copied.');
end;
uses
shellApi;
{...}
procedure TForm1.Button1Click(Sender: TObject);
const
ExtrFileName = 'C:\WINNT\system32\moricons.dll';
var
icon: TIcon;
NumberOfIcons, i: Integer;
begin
icon := TIcon.Create;
try
// Get the number of Icons
NumberOfIcons := ExtractIcon(Handle, PChar(ExtrFileName), UINT(-1));
ShowMessage(Format('%d Icons', [NumberOfIcons]));
// Extract the first 5 icons
for i := 1 to 5 do
begin
// Extract an icon
icon.Handle := ExtractIcon(Handle, PChar(ExtrFileName), i);
// Draw the icon on your form
DrawIcon(Form1.Canvas.Handle, 10, i * 40, icon.Handle);
end;
finally
icon.Free;
end;
end;
// Note: If you are not using Delphi 4 you can remove the UINT.
function IsFileInUse(FileName: TFileName): Boolean;
var
HFileRes: HFILE;
begin
Result := False;
if not FileExists(FileName) then Exit;
HFileRes := CreateFile(PChar(FileName),
GENERIC_READ or GENERIC_WRITE,
0,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
Result := (HFileRes = INVALID_HANDLE_VALUE);
if not Result then
CloseHandle(HFileRes);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if IsFileInUse('c:\Programs\delphi6\bin\delphi32.exe') then
ShowMessage('File is in use.');
else
ShowMessage('File not in use.');
end;
{
FindExecutable returns the name and handle to the executable
(.EXE) file associated with a specified file type (.BMP)
}
{
Wenn du z.B eine BMP-Datei anklickst, wird die
dazugehörige Anwendung MSPAINT.EXE mit der Datei als
Parameter ausgeführt. In diesem Beispiel wird
herausgefunden, welche Anwendung (hier MSPAINT.EXE)
mit dem jeweiligen Datei Typ verknüpft ist.
}
function ShellFindExecutable(const FileName, DefaultDir: string): string;
var
Res: HINST;
Buffer: array[0..MAX_PATH] of Char;
P: PChar;
begin
FillChar(Buffer, SizeOf(Buffer), #0);
if DefaultDir = '' then P := nil
else
P := PChar(DefaultDir);
Res := FindExecutable(PChar(FileName), P, Buffer);
if Res > 32 then
begin
P := Buffer;
while PWord(P)^ <> 0 do
begin
if P^ = #0 then // FindExecutable replaces #32 with #0
P^ := #32;
Inc(P);
end;
Result := Buffer;
end
else
Result := '';
end;
// Example, Beispiel:
procedure TForm1.Button1Click(Sender: TObject);
begin
ShellFindExecutable('1stboot.bmp', 'c:\windows');
end;
function GetVersion: string;
var
VerInfoSize: DWORD;
VerInfo: Pointer;
VerValueSize: DWORD;
VerValue: PVSFixedFileInfo;
Dummy: DWORD;
begin
Result := '';
VerInfoSize := GetFileVersionInfoSize(PChar(ParamStr(0)), Dummy);
if VerInfoSize = 0 then Exit;
GetMem(VerInfo, VerInfoSize);
GetFileVersionInfo(PChar(ParamStr(0)), 0, VerInfoSize, VerInfo);
VerQueryValue(VerInfo, '\', Pointer(VerValue), VerValueSize);
with VerValue^ do
begin
Result := IntToStr(dwFileVersionMS shr 16);
Result := Result + '.' + IntToStr(dwFileVersionMS and $FFFF);
Result := Result + '.' + IntToStr(dwFileVersionLS shr 16);
Result := Result + '.' + IntToStr(dwFileVersionLS and $FFFF);
end;
FreeMem(VerInfo, VerInfoSize);
end;
function MinimizeToTray(Handle: HWND): Boolean;
var
hwndTray: HWND;
rcWindow: TRect;
rcTray: TRect;
begin
// Check passed window handle
if IsWindow(Handle) then
begin
// Get tray handle
hwndTray := FindWindowEx(FindWindow('Shell_TrayWnd', nil), 0, 'TrayNotifyWnd', nil);
// Check tray handle
if (hwndTray = 0) then
// Failure
Result := False
else
begin
// Get window rect and tray rect
GetWindowRect(Handle, rcWindow);
GetWindowRect(hwndTray, rcTray);
// Perform the animation
DrawAnimatedRects(Handle, IDANI_CAPTION, rcWindow, rcTray);
// Hide the window
ShowWindow(Handle, SW_HIDE);
end;
end
else
// Failure
Result := False;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
MinimizeToTray(Handle);
end;