-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLightCore.IO.pas
More file actions
2589 lines (1975 loc) · 93.1 KB
/
LightCore.IO.pas
File metadata and controls
2589 lines (1975 loc) · 93.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
UNIT LightCore.IO;
{=============================================================================================================
2026.01.30
www.GabrielMoraru.com
--------------------------------------------------------------------------------------------------------------
Super useful functions for file/folder/disk manipulation:
- Copy files
- File/Folder exists
- Get special Windows folders (My Documents, etc)
- Prompt user to select a file/folder
- List specified files (*.jpg for ex) in a folder and all its sub-folders
- Increment the numbers in a filename (good for incremental backups)
- Append strings to file name
- Read text from files to a string variable
- Compare files
- Merge files
- Sort lines in a file
- Drive manipulation (IsDiskInDrive, etc)
- etc
Cross-platform ready: stamped 2026.01
==============================================================================================================
EXISTS:
procedure ProcessPath (FullFileName, Drive, DirPart, FilePart) // Parses a file name into its constituent parts.
procedure CutFirstDirectory(VAR S: TFileName)
procedure FileGetSymLinkTarget // Reads the contents of a symbolic link. The result is returned in the symbolic link record given by SymLinkRec.
------------------------------------------------
Maximum Path Length Limitation
In the Windows API (with some exceptions), the maximum length for a path is MAX_PATH,
which is defined as 260 characters. A local path is structured in the following order:
drive letter, colon, backslash, name components separated by backslashes, and a terminating null character.
Example: "D:\some 256-character-path-string<NUL>" -> 256
Using long paths
The Windows API has many functions that also have Unicode versions to permit an extended-length path
for a maximum total path length of 32,767 characters.
In order to name a path with a long name you need to use the magic \\?\ prefix, and use the Unicode version of the API.
For example, "\\?\D:\very long path".
WinApi.Windows.MAX_PATH is declared as MAX_PATH = 260;
Relative paths
Relative paths are always limited to a total of MAX_PATH characters.
Enable Long Paths in Win10
Starting in Windows 10.1607, MAX_PATH limitations have been removed from common Win32 file and directory functions.
However, you must opt-in to the new behavior.
From Microsoft documentation:
https://stackoverflow.com/questions/6996711/how-to-create-directories-in-windows-with-path-length-greater-than-256/59641690#59641690
IOUtils
TFile.FCMinFileNameLen = 12.
There is a problem in IOUtils. It cannot be used in conjunction with Max_Path.
It uses InternalCheckDirPathParam all over the place!
So, instead of using MAX_PATH we use MAXPATH declared below
Details: https://stackoverflow.com/questions/44141996/tdirectory-getdirectoryroot-does-not-accept-paths-of-max-path-characters
------------------------------------------------
SEE THIS FOR Mac OSX
http://www.malcolmgroves.com/blog/?p=865
TESTER:
c:\MyProjects\LightSaber\UNC Tester\
==================================================================================================}
//todo 1: check this file to make sure it also works on Android.
INTERFACE
USES
System.Generics.Collections,
System.Generics.Defaults,
System.Diagnostics,
System.Math,
System.Masks,
System.Types,
System.StrUtils,
System.IOUtils,
System.SysUtils,
System.Classes;
CONST
DigSubdirectories = TRUE;
UseFullPath = TRUE;
{$IFDEF MSWINDOWS}
MAXPATH= 260-12;
{$ELSE}
MAXPATH= 4095;
{$ENDIF}
{ FILTERS }
FilterTxt = 'TXT file|*.TXT';
FilterRtf = 'RTF file|*.RTF';
{}
fltCsv = '*.csv';
FilterCsv = 'CSV file|'+ fltCsv;
{}
FilterAllFiles= 'All files|*.*'; { See also Vcl.Consts.SDefaultFilter }
{}
fltIni = '*.ini';
FilterIni = 'INI file|'+ fltIni;
FilterTransl = 'Translation file|'+ fltIni;
{}
FilterHtm = 'HTM|*.htm';
FilterHtml = 'HTML|*.html';
{}
ctFltSounds = 'Sound (Wav, mp3, midi, wma)|*.wav;*.mp3;*.mi*;*.au;*.wma';
ctFltIcons = 'Icons (*.ico)|*.ico';
{}
FilterApps = 'Applications|*.exe';
Executables = '*.exe;*.cmd;*.bat;*.dll;*.ocx';
{ GRAPH FILTERS }
// Also see this FMX function: TBitmapCodecManager.GetFileTypes.
JPG = '*.jpg;*.jpeg;*.jpe;*.jp;*.jfif';
JPGFtl = 'JPEG|'+ JPG;
JPG2k = '*.J2K;*JPC;*.JP2';
JPG2kFtl = 'JPEG 2000|'+ JPG2k;
JPGAll = JPG+ ';'+ JPG2k;
JPGAllFlt = JPGFtl+ '|'+ JPG2kFtl;
BmpType = '*.BMP'; // Also you can use: GraphicExtension(TBitmap)
BMPFtl = 'Bitmaps|'+ BmpType;
PNG = '*.PNG';
PNGFtl = 'PNG|'+ PNG;
GIF = '*.GIF';
GIFFtl = 'GIF|'+ GIF;
XMF = '*.EMF;*.WMF';
XMFFtl = 'Microsoft EMF/WMF|'+ XMF;
AllImg = JPG+ ';'+ JPG2k+ ';'+ BmpType+ ';'+ PNG+ ';'+ GIF;
AllImgFlt = 'Images|'+ AllImg;
AllImgFltLong = AllImgFlt+ '|'+ JPGFtl+ '|'+ JPG2kFtl+ '|'+ BMPFtl+ '|'+ PNGFtl+ '|'+ GIFFtl+ '|'+ XMFFtl;
{--------------------------------------------------------------------------------------------------
MULTIPLATFORM / LINUX PATHS
--------------------------------------------------------------------------------------------------}
{ Trail }
function TrailLinuxPathEx (CONST Path: string): string; { Adds / in front and at the end of the path }
function TrailLinuxPath (CONST Path: string): string; { Adds / at the end of the path }
function TrimLastLinuxSeparator (CONST Path: string): string;
{ CONVERSION }
function Convert2LinuxPath (CONST DosPath : string): string;
function Convert2DosPath (CONST LinuxPath: string): string;
{--------------------------------------------------------------------------------------------------
EXISTS
--------------------------------------------------------------------------------------------------}
function IsFolder (CONST FullPath: string): boolean; { Tells if FullPath is a folder or file. THE FOLDER/FILE MUST EXISTS!!! }
function DirectoryExists (CONST Directory: String; FollowLink: Boolean= TRUE): Boolean; { Corectez un bug in functia 'DirectoryExists' care imi intoarce true pentru un folder care nu exista, de exemplu 'c:\Program Files\ '. Bug-ul apare cand calea se termina cu un caracter SPACE. }
{--------------------------------------------------------------------------------------------------
VALIDITY
--------------------------------------------------------------------------------------------------}
function FileNameIsValid_ (CONST FileName: string): Boolean; deprecated 'Use System.IOUtils.TPath.HasValidFileNameChars instead.'
function PathNameIsValid (CONST Path: string): Boolean; { TPath.HasValidPathChars is bugged - Returns FALSE if the path contains invalid characters. Tells nothing about the existence of the folder }
function IsUnicode (CONST Path: string): boolean; { Returns True if this path seems to be UNICODE }
{--------------------------------------------------------------------------------------------------
PROCESS PATH
--------------------------------------------------------------------------------------------------}
function ExtractLastFolder (FullPath: string): string; { exemplu pentru c:\windows\system intoarce doar 'system' }
function ExtractParentFolder (CONST Folder: string): string;
function ExtractFirstFolder (CONST Folder: string): string; { For c:\1\2\3\ returns 1\. From c:\1 it returns '' }
function TrimLastFolder (CONST DirPath: string): string; { exemplu pentru c:\windows\system intoarce doar 'c:\windows\' }
function ExtractRelativePath_ (CONST FullPath, RelativeTo: string): string; deprecated 'Use System.SysUtils.ExtractRelativePath instead' { Returns truncated path, relative to 'RelativeTo'. Example: ExtractRelativePath('c:\windows\system32\user32.dll', 'c:\windows') returns system32\user32.dll }
function ShortenFileName (CONST FullPath: String; MaxLength: Integer= MAXPATH): string; { Returns a valid path, but with shorter filename }
function CheckPathLength (CONST FullPath: string; MaxLength: Integer= MAXPATH): Boolean;
{ Path delimiters }
function ForcePathDelimiters (CONST Path, Delimiter: string; SetAtBegining, SetAtEnd: Boolean): string; { Old name: UniversalPathDelimiters }
function Trail (CONST Path: string): string; { Replacement for includeTrailingPathDelimiter }
//See also: SysUtil.SameFileName
function SameFolder(Path1, Path2: string): Boolean; { Receives two folders. Ex: C:\Test1\ and C:\teSt1 will return true }
function SameFolderFromFile(Path1, Path2: string): Boolean; { Receives two partial or complete file names and compare their folders. Ex: C:\Test1 and C:\teSt1\me.txt will return true }
function IsSubfolder(Path1: String; Path2: String): Boolean;
{--------------------------------------------------------------------------------------------------
CREATE FOLDERS
--------------------------------------------------------------------------------------------------}
procedure ForceDirectoriesE (CONST Folder: string);
function ForceDirectoriesB (CONST Folder: string): Boolean; { Replacement for System.SysUtils.ForceDirectories - elimina problema: " { Do not call ForceDirectories with an empty string. Doing so causes ForceDirectories to raise an exception" }
function ForceDirectories (CONST Folder: string): Integer;
{--------------------------------------------------------------------------------------------------
FIX PATH
--------------------------------------------------------------------------------------------------}{ Old name: RemoveInvalidPathChars }
function CorrectFolder (CONST Folder : string; ReplaceWith: char= ' '): string; { Folder is single folder. Example '\test\' }
function CorrectFilename (CONST FileName: string; ReplaceWith: char= ' '): string; { Correct invalid characters in a filename. FileName = File name without path }
{--------------------------------------------------------------------------------------------------
TEXT RELATED
--------------------------------------------------------------------------------------------------}
function ShortenPath (CONST LongPath: String; MaxChars: Integer): String; { Also exists: FileCtrl.MinimizeName, DrawStringEllipsis }
{--------------------------------------------------------------------------------------------------
SPECIAL FOLDERS
--------------------------------------------------------------------------------------------------}
function GetTempFolder : string;
function GetMyDocuments : string; { See this for macosx: http://www.malcolmgroves.com/blog/?p=865 }
function GetMyPictures : string;
function GetHomePath: string;
function GetDocumentsPath: string;
function GetSharedDocumentsPath: string;
function GetMusicPath: string;
function GetMoviesPath: string;
function GetDownloadsPath: string;
function GetLibraryPath: string;
function GetCachePath: string;
function GetPublicPath: string;
function GetRandomFileName: string;
function GetTempFileName: string;
{--------------------------------------------------------------------------------------------------
LIST FOLDER CONTENT
--------------------------------------------------------------------------------------------------}
function ListDirectoriesOf (CONST aFolder: string; CONST ReturnFullPath, DigSubdirectories: Boolean): TStringList; { if DigSubdirectories is false, it will return only the top level directories, else it will return also the subdirectories of subdirectories. Returned folders are FullPath. Works also with Hidden/System folders }
function ListFilesAndFolderOf(CONST aFolder: string; CONST ReturnFullPath: Boolean): TStringList;
function ListFilesOf (CONST aFolder, FileType: string; CONST ReturnFullPath, DigSubdirectories: Boolean; ExcludeFolders: TStrings= nil): TStringList;
function FolderIsEmpty (CONST FolderName: string): Boolean; { Check if folder is empty }
function CountFilesInFolder (CONST Path: string; CONST SearchSubFolders, CountHidden: Boolean): Cardinal;
{--------------------------------------------------------------------------------------------------
FILE AUTO-NAME
--------------------------------------------------------------------------------------------------}
function GetTimestampFileName(CONST Folder, Prefix, Extension: string): string;
function IncrementFileNameEx (CONST FileName: string; StartAt, NumberLength: Integer): string; { Same sa IncrementFileName but it automatically adds a number if the file doesn't already ends with a number }
function IncrementFileName (CONST FileName: string; AddDash: Boolean = false): string; { Receives a file name that ends in a number. returns the same filename plus the number incremented with one. }
function MakeUniqueFolderName (CONST RootPath, FolderName: string): string; { Returns a unique path ended with a number. Old name: Getnewfoldername }
function ChangeFilePath (CONST FullFileName, NewPath: string): string; { Change file path to NewPath }
function AppendNumber2Filename(CONST FileName: string; StartAt, NumberLength: Integer): string; { Add the number at the end of the filename. Example: AppendNumber2Filename('Log.txt', 1) will output 'Log1.txt' }
function FileEndsInNumber (CONST FileName: string): Boolean; { Returns true is the filename ends with a number. Example: MyFile02.txt returns TRUE }
// function GetUniqueFileName: string; //replaced by LightCore.GenerateUniqueString
{--------------------------------------------------------------------------------------------------
CHANGE FILENAME
--------------------------------------------------------------------------------------------------}
function AppendToFileName (CONST FileName, ApendedText: string): string; { Add a string between the name and the extension. Example: if I add the string ' backup' to the file 'Shell32.DLL' -> 'Shell32 backup.DLL' }
function AppendBeforeName (CONST FullPath, ApendedText: string): string; { Add a string between the last directory separator and the beginning of the file name. Example: if I add the string ' backup' to the file 'c:\Shell32.DLL' -> 'c:\backup Shell32.DLL' -> 'c:\backup Shell32.DLL' -> 'c:\backup Shell32.DLL'. }
function ReplaceOnlyName (CONST FileName, newName: string): string; { Replaces ONLY the name of a file (no extension) in a full path. Example: C:\Name.dll -> C:\NewName.dll }
{--------------------------------------------------------------------------------------------------
EXTRACT FILENAME
--------------------------------------------------------------------------------------------------}
function RemoveDrive (CONST FullPath: string): string; { C:\MyDocuments\1.doc -> MyDocuments\1.doc }
function ExtractDrive (CONST FullPath: string): string; { C:\MyDocuments\1.doc -> C }
function ExtractFilePath (CONST FullPath: string; AcceptInvalidPaths: Boolean= TRUE): string;{ Same as the old ExtractFilePath but uses the new GetDirectoryName function instead }
function ExtractOnlyName (CONST FileName: string): string; { Extracts the name of a file. If the name is of type name+extension+extension, only the last extension will be removed. Use the new IOUtils library }
{--------------------------------------------------------------------------------------------------
FILE EXTENSION
--------------------------------------------------------------------------------------------------}
function RemoveLastExtension (CONST FileName: string): string; { Extrage numele fisierului din nume+extensie. Daca numele este de tipul nume+extensie+extensie, doar ultima extensie este eliminata }
function ForceExtension (CONST FileName, Ext: string): string; { Makes sure that the 'FileName' file has the extension set to 'Ext'. The 'Ext' parameter should be like: '.txt' }
function ExtractFileExtUp (CONST FileName: string): string; { Case insensitive version }
function AppendFileExtension (CONST FileName, Ext: string): string;
{--------------------------------------------------------------------------------------------------
FILE TYPE
--------------------------------------------------------------------------------------------------}
function IsThisType (CONST AFile, FileType: string) : Boolean; { Returns true if the specified file is of the 'FileType' type }
function IsVideo (CONST AGraphFile: string) : Boolean; { Video files supported by FFVCL (cFrameServerAVI) }
function IsVideoGeneric(CONST AGraphFile: string) : Boolean; { Generic video file detection. It doesn't mean I have support for all those files in my app }
function IsGIF (CONST AGraphFile: string) : Boolean;
function IsJpg (CONST AGraphFile: string) : Boolean;
function IsJp2 (CONST AGraphFile: string) : Boolean;
function IsBMP (CONST AGraphFile: string) : Boolean;
function IsWebP (CONST AGraphFile: string) : Boolean;
function IsPNG (CONST AGraphFile: string) : Boolean;
function IsWB1 (CONST AGraphFile: string) : Boolean;
function IsWBC (CONST AGraphFile: string) : Boolean;
function IsICO (CONST AGraphFile: string) : Boolean;
function IsEMF (CONST AGraphFile: string) : Boolean;
function IsWMF (CONST AGraphFile: string) : Boolean;
function IsImage (CONST AGraphFile: string) : Boolean; { Returns TRUE if the file has a good/known extension and it can be converted to BMP }
function IsImage2Bmp (CONST AGraphFile: string) : Boolean;
function IsText (CONST FileName: string) : Boolean;
function IsDocument (CONST FileName: string) : Boolean;
function IsDfm (CONST FileName: string) : Boolean;
function IsPas (CONST FileName: string) : Boolean;
function IsDpr (CONST FileName: string) : Boolean;
function IsDpk (CONST FileName: string) : Boolean;
function IsDelphi (CONST FileName: string) : Boolean;
function IsExec (CONST FileName: string) : Boolean;
function ExtensionToMimeType (CONST FileName: string): string; // Determines the MIME type of a file based on its extension
function ExtensionFromMimeType(CONST MimeType: string): string; // Determines the file extension based on a given MIME type
{--------------------------------------------------------------------------------------------------
FILE BINARY COMPARE
--------------------------------------------------------------------------------------------------}
function CompareStreams (A, B: TStream; BufferSize: Integer = 4096): Boolean;
function CompareFiles (CONST FileA, FileB: TFileName; BufferSize: Integer = 4096): Boolean;
{--------------------------------------------------------------------------------------------------
FILE MERGE
--------------------------------------------------------------------------------------------------}
procedure CopyFileTop (CONST SourceName, DestName: string; CopyBytes: Int64); { Copy only CopyBytes bytes from the begining of the file }
procedure AppendTo (CONST MasterFile, SegmentFile, Separator: string; SeparatorFirst: Boolean= TRUE); { Append Segment to Master. Master must exists. }
procedure MergeFiles (CONST InpFile1, InpFile2, OutputFile, Separator: string; SeparatorFirst: Boolean= TRUE); overload;
function MergeFiles (CONST Folder, FileType, OutputFile, Separator: string; DigSubdirectories: Boolean= FALSE; SeparatorFirst: Boolean= TRUE): Integer; overload;
{ OTHERS }
function BytesToFile (CONST FileName: string; CONST Data: TBytes; CONST Overwrite: Boolean= TRUE): Boolean;
{System.IOUtils.TFile.Encrypt https://docwiki.embarcadero.com/Libraries/Alexandria/en/System.IOUtils.TFile.Encrypt - Encrypt a given file using the operating system-provided facilities.}
{--------------------------------------------------------------------------------------------------
COPY/MOVE
--------------------------------------------------------------------------------------------------}
{COPY FILES}
function CopyFile (CONST SourceName, DestName: string): Boolean;
function FileCopyQuick (CONST From_FullPath, To_DestFolder: string): boolean; { in this function you don't have to provide the full path for the second parameter but only the destination folder }
{MOVE FILES}
function FileMoveTo (CONST From_FullPath, To_FullPath : string): Boolean;
function FileMoveToDir (CONST From_FullPath, To_DestFolder: string): Boolean;
{FOLDERS}
function CopyFolder (CONST FromFolder, ToFolder : String; Overwrite: Boolean= True; CONST FileType: string= '*.*'): integer; { copy a folder and all its files and subfolders }
function MoveFolderRel (CONST FromFolder, ToRelFolder: string; Overwrite: Boolean= True): string;
procedure MoveFolder (CONST FromFolder, ToFolder : String; SilentOverwrite: Boolean= True);
function MoveFolderSlow (CONST FromFolder, ToFolder : String; Overwrite: boolean): Integer; deprecated 'Use TDirectory.Move() instead.';
{--------------------------------------------------------------------------------------------------
BACKUP
--------------------------------------------------------------------------------------------------}
function BackupFileIncrement (CONST FileName: string; CONST DestFolder: string= ''; const NewExtension: string= '.bak'): string; { Creates a copy of this file in the new folder. Automatically increments its name. Returns '' in case of copy failure }
function BackupFileBak (CONST FileName: string): Boolean; { Creates a copy of this file, and appends as file extension. Ex: File.txt -> File.txt.bak }
function BackupFileDate (CONST FileName: string; TimeStamp: Boolean= TRUE; Overwrite: Boolean = TRUE): Boolean; overload; { Create a copy of the specified file in the same folder. The '_backup' string is attached at the end of the filename }
function BackupFileDate (CONST FileName, DestFolder: string; TimeStamp: Boolean= TRUE; Overwrite: Boolean = TRUE): Boolean; overload;
{--------------------------------------------------------------------------------------------------
DELETE
--------------------------------------------------------------------------------------------------}
procedure EmptyDirectory (CONST Path: string); { Delete all files in the specified folder, but don't delete the folder itself. It will search also in subfolders }
procedure DeleteFolder (CONST Path: string);
procedure RemoveEmptyFolders (CONST RootFolder: string); { Not tested! Delete all empty folders / sub-folders (any sub level) under the provided "rootFolder" }
function TryDeleteFile (CONST FileName: string): Boolean;
{--------------------------------------------------------------------------------------------------
FILE SIZE
--------------------------------------------------------------------------------------------------}
function GetFileSize (CONST FileName: string): Int64;
function GetFileSizeFormat(CONST FileName: string): string; { Same as GetFileSize but returns the size in b/kb/mb/etc }
function GetFolderSize (CONST Folder: string; CONST FileType: string= '*.*'; DigSubdirectories: Boolean= TRUE): Int64;
{--------------------------------------------------------------------------------------------------
FILE TIME
--------------------------------------------------------------------------------------------------}
function ExtractTimeFromFileName (CONST FileName: string): TTime; { The time must be at the end of the file name. Example: 'MyPicture 20-00.jpg'. Returns -1 if the time could not be extracted. }
function DateToStr_IO (CONST DateTime: TDateTime): string; { Original name: StrTimeToSeconds_unsafe }
function TimeToStr_IO (CONST DateTime: TDateTime): string;
function DateTimeToStr_IO (CONST DateTime: TDateTime): string; overload; { Used to conver Date/Time to a string that is safe to use in a path. For example, instead of '2013/01/01' 15:32 it will return '2013-01-01 15,32' }
function DateTimeToStr_IO: string; overload;
{--------------------------------------------------------------------------------------------------
DRIVES
--------------------------------------------------------------------------------------------------}
function ExtractDriveLetter (CONST Path: string): char; deprecated 'Use IOUtils.TDirectory.GetDirectoryRoot instead.' { Returns #0 for invalid or network paths. GetDirectoryRoot returns something like: 'C:\' }
{ Validity }
function ValidDriveLetter (CONST Drive: Char): Boolean; { Returns false if the drive letter is not in ['A'..'Z'] }
function DriveProtected (CONST Drive: Char): Boolean; { Attempt to create temporary file on specified drive. If created, the temporary file is deleted. } {old name: IsDiskWriteProtected }
{ Convert }
function Drive2Byte (CONST Drive: Char): Byte; { Converts the drive letter to the number of that drive. Example drive "A:" is 1 and drive "C:" is 3 }
function Drive2Char (CONST DriveNumber: Byte): Char; { Converts the drive number to the letter of that drive. Example drive 1 is "A:" floppy }
function GetLogicalDrives: TStringDynArray; inline;
IMPLEMENTATION
USES
LightCore;
{--------------------------------------------------------------------------------------------------
LINUX
--------------------------------------------------------------------------------------------------}
{ Adds / in front and at the end of the path }
function TrailLinuxPathEx(CONST Path: string): string;
begin
Result:= Path;
if Path > '' then
begin
if FirstChar(Result) <> '/'
then Result:= '/'+ Result;
if LastChar(Result) <> '/'
then Result:= Result+ '/';
end;
end;
{ Adds / at the end of the path }
function TrailLinuxPath(CONST Path: string): string;
begin
if (Path > '')
AND (LastChar(Path) <> '/')
then Result:= Path+ '/'
else Result:= Path;
end;
function TrimLastLinuxSeparator(CONST Path: string): string;
begin
if LastChar(Path) = '/'
then Result:= LightCore.RemoveLastChar(Path)
else Result:= Path;
end;
{ Converts DOS path to Linux path by replacing backslashes with forward slashes.
Does not handle the drive letter (C:), only the path separators. }
function Convert2LinuxPath(CONST DosPath: string): string;
begin
Result:= ReplaceCharF(DosPath, '\', '/');
end;
function Convert2DosPath(CONST LinuxPath: string): string;
begin
Result:= ReplaceCharF(LinuxPath, '/', '\');
end;
{--------------------------------------------------------------------------------------------------
FOLDER
--------------------------------------------------------------------------------------------------}
{ Returns True if this path uses the extended-length path prefix (\\?\).
These paths support paths longer than MAX_PATH (260 chars) in Windows.
See: https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation }
function IsUnicode(CONST Path: string): boolean;
begin
Result:= Pos('\\?\', Path) = 1;
end;
{ Returns True if FullPath is an EXISTING directory.
Returns False if it's a file or doesn't exist.
Works with UNC paths.
See: stackoverflow.com/questions/63606215 }
function IsFolder(CONST FullPath: string): boolean;
begin
Result:= DirectoryExists(FullPath);
end;
{ Appends the 'Delimiter' at the beginning and/or end of the Path if not already present.
Works with UNC paths.
Delimiter should be a single character string (e.g., '/' or '\'). }
function ForcePathDelimiters(CONST Path, Delimiter: string; SetAtBegining, SetAtEnd: Boolean): string;
begin
if (Path = '') OR (Delimiter = '')
then EXIT(Path);
Result:= Path;
if SetAtBegining AND (Result[1] <> Delimiter[1])
then Result:= Delimiter + Result;
if SetAtEnd AND (Result[Length(Result)] <> Delimiter[1])
then Result:= Result + Delimiter;
end;
{ Works with UNC paths }
function Trail(CONST Path: string): string;
begin
if Path= '' then EXIT(''); { I may encounter this when I do this: ExtractLastFolder('c:\'). ExtractLastFolder will return '' }
Result:= IncludeTrailingPathDelimiter(Path);
end;
{ Check if folder is empty }
function FolderIsEmpty(const FolderName: string): Boolean;
begin
Result:= TDirectory.IsEmpty(FolderName);
end;
{ Ex: C:\Test1\ and C:\teSt1 will return true }
function SameFolder(Path1, Path2: string): Boolean;
begin
Path1:= Trail(Path1);
Path2:= Trail(Path2);
Result:= SameText(Path1, Path2);
end;
{ Receives two partial or complete file names and compare their folders.
Ex: C:\Test1 and C:\teSt1\me.txt will return true }
function SameFolderFromFile(Path1, Path2: string): Boolean;
begin
Path1:= ExtractFilePath(Path1);
Path2:= ExtractFilePath(Path2);
Path1:= Trail(Path1);
Path2:= Trail(Path2);
Result:= SameText(Path1, Path2);
end;
{ The order of the parameters does not matter: Path1 could be a subfolder or Path2 or the viceversa }
function IsSubfolder(Path1: String; Path2: String): Boolean;
var
Length1: Integer;
Length2: Integer;
begin
Result := False;
Length1 := Length(Path1);
Length2 := Length(Path2);
If (Length1>0) and (Length2>0) then
begin
Path1 := UpperCase(ExcludeTrailingPathDelimiter(Path1));
Path2 := UpperCase(ExcludeTrailingPathDelimiter(Path2));
If Length1 > Length2
then Result := (Pos(Path2, Path1) = 1)
else Result := (Pos(Path1, Path2) = 1)
end;
end;
{ Returns a shortened path that fits within MaxLength characters.
Shortens the filename portion while preserving the directory path and extension.
WARNING: The caller must ensure the resulting filename has at least 1 character!
If the path alone exceeds MaxLength, the result will be invalid.
IMPORTANT: We cannot use TPath here because it cannot handle long file names.
See: stackoverflow.com/questions/31427260
Related functions:
FileCtrl.MinimizeName - Shortens for pixel width
cGraphics.DrawStringEllipsis- Visual ellipsis
LightCore.ShortenString - General string shortening }
function ShortenFileName(CONST FullPath: String; MaxLength: Integer= MAXPATH): string;
VAR
FilePath, ShortenedFileName: string;
ResultedFileLength: Integer;
begin
ResultedFileLength:= Length(FullPath);
if ResultedFileLength > MaxLength
then
begin
FilePath:= Trail(System.SysUtils.ExtractFilePath(FullPath)); { IMPORTANT! We cannot use TPath here because it cannot handle long file names }
ResultedFileLength:= MaxLength - Length(FilePath) - Length(ExtractFileExt(FullPath));
ShortenedFileName := system.COPY(FullPath, Length(FilePath)+ 1, ResultedFileLength);
Result:= FilePath+ ShortenedFileName+ ExtractFileExt(FullPath);
end
else Result:= FullPath;
end;
{ Checks if the path length is within the allowed limit.
Extended-prefixed paths (\\?\) are not restricted by MaxLength on Windows.
On POSIX systems, checks the UTF-8 encoded byte length. }
function CheckPathLength(const FullPath: string; MaxLength: Integer= MAXPATH): Boolean;
begin
{$IFDEF MSWINDOWS}
{ Extended-length paths (\\?\) bypass the MAX_PATH limit }
Result:= TPath.IsExtendedPrefixed(FullPath) OR (Length(FullPath) < MaxLength);
{$ENDIF MSWINDOWS}
{$IFDEF POSIX}
Result:= (Length(UTF8Encode(FullPath)) < MaxLength);
{$ENDIF POSIX}
end;
{--------------------------------------------------------------------------------------------------
FOLDER VALIDITY
Works with UNC paths
Correct invalid characters in a path. Path = path with filename, like: c:\my docs\MyFile.txt
--------------------------------------------------------------------------------------------------}
function CorrectFolder(CONST Folder: string; ReplaceWith: Char): string; { Old name: CorrectPath, RemoveInvalidPathChars }
VAR i: Integer;
InvalidChars: TCharArray;
begin
{TODO: Make it work with UNC paths! }
InvalidChars := TPath.GetInvalidPathChars;
Result:= Folder;
for i:= 1 to Length(Result) DO
if (Result[i] < ' ') or CharInArray(Result[i], InvalidChars)
then Result[i]:= ReplaceWith;
end;
{
Returns FALSE if the path is too short or contains invalid characters.
Tells nothing about the existence of the folder.
Note: TPath.HasValidPathChars is bugged. https://stackoverflow.com/questions/45346525/why-tpath-hasvalidpathchars-accepts-as-valid-char-in-a-path/45346869#45346869
}
function PathNameIsValid(CONST Path: string): Boolean;
begin
{ToDo: Accept UNC paths like: \??\Windows. For this check for the \?? patern }
Result:= (Path <> '') AND TPath.HasValidPathChars(Path, FALSE);
end;
{ DOESN'T WORK WITH UNC PATHS !!!!!!!!!
Deprecated 'Use System.IOUtils.TPath.HasValidFileNameChars instead.'
HasValidFileNameChars only work with file names, not also with full paths. }
function FileNameIsValid_(CONST FileName: string): Boolean;
VAR i, Spaces: Integer;
InvalidChars: TCharArray;
begin
InvalidChars := TPath.GetInvalidFileNameChars;
if Length(FileName) > 0
then Result:= TRUE
else EXIT(FALSE);
{ File name cannot contain only spaces }
Spaces:= 0;
for i := 1 to Length(FileName) DO
if FileName[i]= ' '
then Inc(Spaces)
else break;
if Spaces= Length(FileName)
then EXIT(FALSE);
{ Check invalid chars }
for i := 1 to Length(FileName) DO
if CharInArray(FileName[i], InvalidChars)
OR (Ord(FileName[i]) < 32)
then EXIT(FALSE);
end;
{--------------------------------------------------------------------------------------------------
FOLDER EXISTENCE
--------------------------------------------------------------------------------------------------}
{ This corrects a bug in the original 'DirectoryExists' which returns true for a folder that does not exist.
The bug appears when the path ends with a SPACE. Exemple: 'c:\Program Files\ '
Works with UNC paths! }
function DirectoryExists(CONST Directory: String; FollowLink: Boolean= TRUE): Boolean;
begin
Result:= System.SysUtils.DirectoryExists(Directory, FollowLink)
{$IFDEF MSWINDOWS}
AND (LastChar(Directory)<> ' ') { Don't accept Space at the end of a path (after the backslash) }
{$ENDIF}
end;
{--------------------------------------------------------------------------------------------------
CREATE FOLDER
Tries to create the specified folder. Does not crashes if
Works with UNC paths.
Writing on a readonly folder: It ignores the ReadOnly attribute (same for H and S attributes)
Returns:
False if the path is invalid.
False if the drive is readonly.
--------------------------------------------------------------------------------------------------}
function ForceDirectoriesB(CONST Folder: string): Boolean;
begin
TRY
TDirectory.CreateDirectory(Folder);
EXCEPT
on EInOutError DO; { Thread race: another thread may have created it. Check actual state below. }
else RAISE;
{
For any other exceptions, raise.
Example:
on EArgumentException DO RAISE; // Re-raise exception for invalid characters in path
on EInOutArgumentException DO RAISE; // 'Path is empty'. }
END;
Result:= DirectoryExists(Folder);
end;
//
//Project Tester_LightCore.IO.exe raised exception class with message
{--------------------------------------------------------------------------------------------------
Raises exception if parameter is invalid
Raises exception if parameter is empty
Raises exception if drive is invalid
--------------------------------------------------------------------------------------------------}
procedure ForceDirectoriesE(CONST Folder: string);
begin
TDirectory.CreateDirectory(Folder);
end;
// Works with UNC paths
function ForceDirectories(CONST Folder: string): Integer;
{RETURNS:
-1 = Error creating the directory
0 = Directory already exists
+1 = Directory created succesfully }
begin
Assert(Folder> '', 'ForceDirectories - Parameter is empty!');
if TDirectory.Exists(Folder)
then Result:= 0
else
if ForceDirectoriesB(Folder)
then Result:= +1
else Result:= -1;
end;
{--------------------------------------------------------------------------------------------------
DETECT FILE TYPE
--------------------------------------------------------------------------------------------------}
{ Returns true if the specified file is of the 'FileType' type.
Example: Check if a file is BMP:
IsThisType('c:\Test.bMP', 'BmP') will return true }
function IsThisType(CONST AFile, FileType: string) : Boolean;
VAR sExtension: string;
begin
sExtension:= ExtractFileExt(AFile);
Result:= SameText(sExtension, '.'+FileType)
end;
{ Video files supported by FFVCL (cFrameServerAVI) }
function IsVideo(CONST AGraphFile: string): Boolean;
VAR sExtension: string;
begin
sExtension:= ExtractFileExtUp(AGraphFile);
Result:=
(sExtension= '.AVI') OR
(sExtension= '.MKV') OR
(sExtension= '.MPEG') OR
(sExtension= '.MP4') OR
(sExtension= '.MP' ) OR
(sExtension= '.MPG') OR
(sExtension= '.WMV') OR
(sExtension= '.VOB') OR
(sExtension= '.ASF') OR
(sExtension= '.OGM') OR
(sExtension= '.AVS') OR
(sExtension= '.MOV') OR
(sExtension= '.3GP') OR
(sExtension= '.RM' ) OR
(sExtension= '.RMVB') OR
(sExtension= '.NSV') OR
(sExtension= '.TP' ) OR
(sExtension= '.TS' ) OR
(sExtension= '.FLV') OR
(sExtension= '.DAT') OR
(sExtension= '.AVM');
end;
{ Generic video file detection. It doesn't mean I have support for all those files in my app }
function IsVideoGeneric(CONST AGraphFile: string): Boolean;
VAR sExtension: string;
begin
sExtension:= ExtractFileExtUp(AGraphFile);
Result:=
{ GLOBAL }
(sExtension= '.AVI') OR
(sExtension= '.MKV') OR
(sExtension= '.DIVX') OR
(sExtension= '.VOB') OR
{ MOTION PICT }
(sExtension= '.MPG') OR
(sExtension= '.MPEG') OR
(sExtension= '.MP4') OR
(sExtension= '.MP2') OR
(sExtension= '.MP') OR
(sExtension= '.M4P') OR
{ MS }
(sExtension= '.ASF') OR
(sExtension= '.WMA') OR
(sExtension= '.WM' ) OR
(sExtension= '.ASX') OR
(sExtension= '.WMV') OR
(sExtension= '.WVX') OR
(sExtension= '.WMX') OR
(sExtension= '.WPL') OR
(sExtension= '.WMD') OR
(sExtension= '.IVF') OR
(sExtension= '.WAX') OR
(sExtension= '.M1V') OR
(sExtension= '.DRV-MS') OR
{ WEB }
(sExtension= '.WEBM') OR
(sExtension= '.F4V') OR
(sExtension= '.FLV') OR
{ MAC }
(sExtension= '.OGV') OR
(sExtension= '.QT') OR
(sExtension= '.MOV') OR
(sExtension= '.RM') OR
{ MOBILE }
(sExtension= '.AMV') OR
(sExtension= '.3GP') OR
(sExtension= '.NSV') OR
{ others }
(sExtension= '.AVM') OR
(sExtension= '.AVS') OR
(sExtension= '.DAT') OR
(sExtension= '.RP' ) OR
(sExtension= '.OGM') OR
(sExtension= '.RMVB') OR
(sExtension= '.TS' );
end;
function IsGIF(CONST AGraphFile: string): Boolean;
begin
Result:= ExtractFileExtUp(AGraphFile)= '.GIF';
end;
function IsJpg(CONST AGraphFile: string): Boolean;
VAR sExtension: string;
begin
sExtension:= ExtractFileExtUp(AGraphFile);
Result:= (sExtension= '.JPG') OR (sExtension= '.JPEG') OR (sExtension= '.JPE') OR (sExtension= '.JFIF') OR (sExtension= '.JP');
end;
function IsJp2(CONST AGraphFile: string): Boolean;
VAR sExtension: string;
begin
sExtension:= ExtractFileExtUp(AGraphFile);
Result:= (sExtension= '.J2K') OR (sExtension= '.JPC') OR (sExtension= '.JP2')
end;
function IsBMP(CONST AGraphFile: string): Boolean;
begin
Result:= ExtractFileExtUp(AGraphFile)= '.BMP';
end;
function IsWB1(CONST AGraphFile: string): Boolean;
begin
Result:= ExtractFileExtUp(AGraphFile)= '.WB1';
end;
function IsWBC(CONST AGraphFile: string): Boolean;
begin
Result:= ExtractFileExtUp(AGraphFile)= '.WBC';
end;
function IsPNG(CONST AGraphFile: string): Boolean;
begin
Result:= ExtractFileExtUp(AGraphFile)= '.PNG';
end;
function IsICO(CONST AGraphFile: string): Boolean;
begin
Result:= ExtractFileExtUp(AGraphFile)= '.ICO';
end;
function IsEMF(CONST AGraphFile: string): Boolean;
begin
Result:= ExtractFileExtUp(AGraphFile)= '.EMF';
end;
function IsWMF(CONST AGraphFile: string): Boolean;
begin
Result:= ExtractFileExtUp(AGraphFile)= '.WMF';
end;
function IsWebP(CONST AGraphFile: string): Boolean;
begin
Result:= ExtractFileExtUp(AGraphFile)= '.WEBP';
end;
function IsImage(CONST AGraphFile: string): Boolean;
begin
Result:=
IsJpg(AGraphFile)
OR IsJp2(AGraphFile)
OR IsBMP(AGraphFile)
OR IsGIF(AGraphFile)
OR IsPNG(AGraphFile)
OR IsWebP(AGraphFile);
end;
{ Returns TRUE if the file has a known extension and it can be converted to BMP }
function IsImage2Bmp(CONST AGraphFile: string): Boolean;
begin
Result:=
IsImage(AGraphFile)
OR IsEMF(AGraphFile)
OR IsWMF(AGraphFile)
OR IsICO(AGraphFile);
end;
{ Determines the MIME type based on file extension.
Returns 'application/octet-stream' for unknown extensions. }
function ExtensionToMimeType(const FileName: string): string;
VAR
Ext: string;
begin
Ext:= LowerCase(ExtractFileExt(FileName));
if Ext = '.txt' then Result:= 'text/plain' else
if Ext = '.md' then Result:= 'text/markdown' else
if Ext = '.pdf' then Result:= 'application/pdf' else
if Ext = '.png' then Result:= 'image/png' else
if Ext = '.gif' then Result:= 'image/gif' else
if Ext = '.webp' then Result:= 'image/webp' else
if (Ext = '.jpg') OR (Ext = '.jpeg') OR (Ext = '.jpe') OR (Ext = '.jfif')
then Result:= 'image/jpeg'
else Result:= 'application/octet-stream';
end;
function ExtensionFromMimeType(const MimeType: string): string;
begin
if MimeType = 'text/plain' then Result := '.txt' else
if MimeType = 'text/markdown' then Result := '.md' else
if MimeType = 'application/pdf' then Result := '.pdf' else
if MimeType = 'image/jpeg' then Result := '.jpg' else
if MimeType = 'image/png' then Result := '.png' else