How to validate ParamStr(1) string as a good path lazarus / 21-General ---------------------------------------------------------------------- lgrfbs · 2024-12-29 08:46 How do I check that the text string coming from ParamStr(1) is a valid path in Windows and Lazarus 3.6? ---------------------------------------------------------------------- cdbc · 2024-12-29 09:05 Hi Hmmm, I would pick apart the paramstr(x), in its separate directories, perhaps with 'Split' on 'PathSeparator' and then start building the path-string dir by dir and along the way check the path-string with 'DirExists' until you have the final input string. If some dirs doesn't exist, just 'MkDir' it as you go along... If you only need to make sure, that the directory path exist, then just use 'ForceDirectories', this function will take care of it all. Regards Benny ---------------------------------------------------------------------- lgrfbs · 2024-12-29 09:39 Thank you for your reply. ParamStr(1) should only contain a path specified by the user to a file that is not created yet, but since users can try to specify information other than a path, I want to check that it is a real path. This is my test so far:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   if ParamCount>1 then  Begin    //https://forum.lazarus.freepascal.org/index.php?topic=15715.0    LE_ProgPath.Text:=ParamStr(1); //Put the path string from user int to LE_ProgPath.Text.     //Did the user end path with '\' or not?    if Copy(LE_ProgPath.Text,Length(LE_ProgPath.Text),1)='\' Then    Begin    //The check did find '\'      LE_ProgPath.Text:=LE_ProgPath.Text+'NC_clean.ini';    End    Else    Begin      // The chek did not find '\', we will add it.      LE_ProgPath.Text:=LE_ProgPath.Text+'\C_clean.ini';    End;     // Is the user path string bigger the 0 in Length?    if Length(ParamStr(1))>0 then    Begin      //IS this string a true path?     Label2.Caption:=ParamStr(1);     Label3.Caption:='Fale';    if DirectoryExists(ParamStr(1)) then      Begin       Label3.Caption:='True';      End;      //Check if the CheckBox 'Deactivete global fontsize controller' named 'CB_GlobalFontSize'    if CB_GlobalFontSize.Checked=True then      Begin        //Deactivate the SpinEdit and ScrollBar        Form1.SE_DirectFontSize.Visible:=False;        Form1.SB_SetFontSize.Visible:=False;      End;      GB_BeforeNC.Visible:=True;      GB_AfterNC.Visible:=True;      GB_PreSelected.Visible:=True;      GB_FontsBox.Visible:=True;    End;  End; ---------------------------------------------------------------------- Bart · 2024-12-29 11:11 Your logic of adding a trailing backslash has a potential problem. If ParamStr(1) is 'C:', this is a valid path, but it means "the current active directory on drive "C". Your code will transfrom that int 'C:\NC_clean.ini', which is definitely not what you want. That aside: your code does exactly what IncludeTrailingPathDelimiter() does. You can rewrite  that part as: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   LE_ProgPa th.Text:=IncludeTrailingPathDelimiter(LE_ProgPath.Text)+'NC_clean.ini' ; Or, if you want to handle the 'C:' case as well: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   if Length(LE_ProgPath.Text > 1) and (LE_ProgPath.Text[Length(LE_ProgPath.Text)] = ':') then    LE_ProgPath.Text := LE_ProgPath.Text + 'NC_clean.ini'  else   LE_ProgP ath.Text:=IncludeTrailingPathDelimiter(LE_ProgPath.Text)+'NC_clean.ini '; What exactly do yo mean by "I want to check that it is a real path"? - A path that actually exists? --> See: DirectoryExists() function - A string that Windows would accept as being a path? --> a bit tricky Bart ---------------------------------------------------------------------- lgrfbs · 2024-12-29 13:35 Thank you for being almost mind readers and asking questions about what I failed to include in my posts. Thank you all. Bart, I have tested your code now and had to adjust it a bit as some ()- characters were missing.Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i     if (Length(LE_ProgPath.Text) > 1) and (LE_ProgPath.Text[Length(LE_ProgPath.Text)] = ':') then      LE_ProgPath.Text := LE_ProgPath.Text + '\NC_clean.ini'    else    LE_P rogPath.Text:=IncludeTrailingPathDelimiter(LE_ProgPath.Text)+'NC_clean .ini'; This code works as I want/expect. QuoteWhat exactly do yo mean by "I want to check that it is a real path"? - A path that actually exists? --> See: DirectoryExists() function - A string that Windows would accept as being a path? --> a bit tricky The option: A path that actually exists? --> See: DirectoryExists() function I will read up on DirectoryExists I've done some testing and on my Windows 10 system C:\ is read-only in the CMD window so my program probably can't put the NC_clean.ini file there even after checking that it's a real path. Typing C: in the cmd window just takes you directly to the drive and folder you were in when you left the drive or opened the CMD window, but for example if I want to see the files in drive C and the root I type DIR C:\ and everything in the root is listed on the screen. If I want to look in a file in the C drive root, when I am not in that folder, for example: type C:\App.txt this will cause the contents of the file to be listed on the screen. The idea is thus that: A; Check that the text the user entered as a path is really a path that exists on the system and discard unknown commands/nonsense text from the user. B; Once the user wants to save their settings in the program to the NC_clean.ini file, the location should be writable. ---------------------------------------------------------------------- Bart · 2024-12-29 15:01 Quote from: lgrfbs on December 29, 2024, 02:35:23 pmTyping C: in the cmd window just takes you directly to the drive and folder you were in when you left the drive or opened the CMD window If you have more than 1 drive, e.g. C: and D: then you can do something like this: Code: [Select]C:\>cd users\bart C:\Users\Bart>d: D:\>cd Boot D:\Boot>c: C:\Users\Bart> Now notice that typing "C:" at the prompt brings me back to "C:\Users\Bart" and not to "C:\". Quote from: lgrfbs on December 29, 2024, 02:35:23 pmThe idea is thus that: A; Check that the text the user entered as a path is really a path that exists on the system and discard unknown commands/nonsense text from the user. That's a bit tricky. You can check for "forbidden characters" , at least '<', '>', '|', '*' and '?' are not allowed on Windows. But, there's an exception to that as well. If a path starts with '\\?\' then everythig after is is treated as a literal character. (You can create folders/files that way, which you cannot delete in Windows Explorer  ) Also, some filenames are forbidden (like: 'CON', 'PRN'). See https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a- file for more information on what is allowed and what not. Quote from: lgrfbs on December 29, 2024, 02:35:23 pmB; Once the user wants to save their settings in the program to the NC_clean.ini file, the location should be writable. Have a look at DirectoryIsWritable() in LazFileUtils unit. If you allow the user to specify a directory that does not exist yet, you could try to use ForceDirectoriesUtf8. It will create the folder if Windows allows it and then return True, it will fail and return False if it cannot create the folder. (If the folder already exists, it will return True as well.) Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   if not ForceDirectoriesUtf8('C:\Users\Bart\Foo\Bar\MySettings') then    ShowMessage('Unable to create folder'); Bart ---------------------------------------------------------------------- jcmontherock · 2024-12-29 15:47 Don't forget also:  FileExists or FileExistsUTF8 functions if file or directory exists. ---------------------------------------------------------------------- lgrfbs · 2024-12-31 16:01 I want to thank you for all the answers I have received so far, so THANK YOU. I will get back to you after 2025 has landed, so Happy New Year to the whole forum. ---------------------------------------------------------------------- silvercoder70 · 2025-01-01 00:34 Quick question... Does the path have to be absolute or can it be relative? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function IsFileOrDirectory(const Path: string): Boolean;var  SearchRec: TSearchRec;begin  Result := False;  // Check if it's a file or directory using FindFirst  if FindFirst(Path, faAnyFile, SearchRec) = 0 then  begin    // Check if it's a directory    if (SearchRec.Attr and faDirectory) <> 0 then      Result := True  // Directory found    // Check if it's a regular file    else      Result := True; // File found    FindClose(SearchRec);  end;end; Depending on your needs you can add code around that. ---------------------------------------------------------------------- n7800 · 2025-01-01 12:23 Quote from: Bart on December 29, 2024, 04:01:21 pmYou can check for "forbidden characters" , at least '<', '>', '|', '*' and '?' are not allowed on Windows. But, there's an exception to that as well. If a path starts with '\\?\' then everythig after is is treated as a literal character. (You can create folders/files that way, which you cannot delete in Windows Explorer  ) Also, some filenames are forbidden (like: 'CON', 'PRN'). See https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a- file for more information on what is allowed and what not. I also wanted to give this link along with this one, which lets many programmers understand that they know nothing about Windows )) But I can't resist making things even more complicated: Path length limitation. For example, paths longer than 260 characters cannot be valid, even if they exist! However, UNC paths can (though they also have a length limitation). And starting with Windows 10, there are changes.WinAPI functions can automatically convert "/" to "\" (and Lazarus/FPC also partially supports this due to cross- platform). So paths through "/" can be valid (or they may not).NTFS file streams ("C:\filename:streamname").8.3 short names ("C:\PROGRA~1").Symbolic links, junctions, hard links.... But seriously, programs shouldn't check all of this. If the first argument is supposed to take a path, the program should assume it's a path. Even if you check all of the above, you may still get an error reading/writing the file (even just because of low disk space or permissions). Utilities should have flags to specify a specific type of parameter, like "-f " for a file and "-m " for some text (or one of the flags can be assumed by default). ---------------------------------------------------------------------- Bart · 2025-01-01 22:49 Quote from: n7800 on January 01, 2025, 01:23:12 pmBut seriously, programs shouldn't check all of this. If the first argument is supposed to take a path, the program should assume it's a path. Even if you check all of the above, you may still get an error reading/writing the file (even just because of low disk space or permissions). Utilities should have flags to specify a specific type of parameter, like "-f " for a file and "-m " for some text (or one of the flags can be assumed by default). Or, if simple commandline program, display the correct syntax upon error (or on suitable commandline parameter like -h, --help /? /h). Bart ---------------------------------------------------------------------- Zvoni · 2025-01-02 07:16 His target is Windows, so i'm not going to look for cross-platform. One of my alltime favorites: https://learn.microsoft.com/en- us/windows/win32/api/shlobj_core/nf-shlobj_core-shcreatedirectoryexw The return-value of it tells you exactly what's going on No idea which unit to include (windows, jwawindows, no idea) ---------------------------------------------------------------------- lgrfbs · 2025-01-12 05:59 I'm sorry it took so long. The reason for my question is that I wanted to be able to save away settings in the program I am creating. One solution would be a button [Save Settings] and the code in that button just dumps all the settings in the program's own folder. However, if the program starts from another folder, the settings file will not be in the “right” place and the program will not load the settings, there by loading the program with the path as a parameter. It could clearly be that I have overthought everything here and just take the parameter and put it in front of the file name and take care of all errors with a dialog box, like: “Something is wrong with the path you specified [Ok]” Another reason why the path is given to the program via parameter is that I want to have the possibility to start the program with the “Start with...” menu item in the Windows file manager. Now I just have to find some inspiration and write some code too... ---------------------------------------------------------------------- Thaddy · 2025-01-12 06:51 Quote from: Zvoni on January 02, 2025, 08:16:43 amNo idea which unit to include (windows, jwawindows, no idea) Shlobj and ShellApi, but jwaWindows is a safe choice because that will pull in a correct file anyway. If I can't find a Windows unit straight away that is my goto trick. ---------------------------------------------------------------------- n7800 · 2025-01-12 09:50 Yes, the JwaWindows description says that it is more complete and allows you to not include many separate units for working with OS Windows. ---------------------------------------------------------------------- Thaddy · 2025-01-12 19:46 I wrote that using jwaWindows is a trick. Take note. It is never the long time solution. ---------------------------------------------------------------------- n7800 · 2025-01-13 02:29 Quote from: Thaddy on January 12, 2025, 08:46:05 pmI wrote that using jwaWindows is a trick. Take note. It is never the long time solution. What do you mean by "trick"? Are there any problems using this unit? ---------------------------------------------------------------------- Thaddy · 2025-01-13 10:22 No, no problems usually, but your executable may become larger than necessary and the compile time may be longer. jwaWindows pulls in all jwa* units in the compile. It is basically an almost empty unit, but with a very long uses clause. But as I wrote, if I can't find a specific windows unit fast enough, I do simply uses jwaWindows... If you are not a professional programmer it really does not matter too much. In that case you have my blessing to use it. There is one point you need to realize: many declarations in jwaWindows differ from the declarations in fpc's windows units. They are actually much better imnsho:fpc's windows units are pointer oriented, whereas jwaWindows uses var for parameters that can not be nil.(i.e. pascalify them properly) If you, like me, prefer that, you will need to find out what particular jwa unit is used and include those instead of all of them, which is what jwaWindows does. If that makes sense to you.