Checking that a string has the format of a valid path lazarus / 21-General ---------------------------------------------------------------------- EganSolo · 2023-04-16 01:50 I want to offer my users the ability to key in or select a path. If they select a path via a dialog, the last directory on the path may or may not exist. The reason is that the creation of the folder should take place once the user is ready to save the entire form. In case the user cancels, the folder should not be created. Is there a method that can perform a syntax check on a string to verify that it obeys the structure of a path? If there isn't, then my approach would consist in writing two functions: 1. function IsValidStrictFileName: a function that validates the portion of a filename without the extension. 2. function IsValidPath:      a. Break the string into tokens by using the Directory delimiter as a separator and store the tokens into a string list called tokens.      b. For each token t in tokens check if (t = '.') or (t = '..') or IsValidStrictFileName(t) Would love your feedback! ---------------------------------------------------------------------- jamie · 2023-04-16 02:39 DirectoryExists or FindFirst ---------------------------------------------------------------------- EganSolo · 2023-04-16 23:02 Here's what I ended up doing. Would love it if you guys could show me how to improve on this code! 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 PathWithoutLastFolder(aPath: String): String;var i : integer;begin  Result := '';  aPath := Trim(aPath);  If aPath = '' then exit;  i := length(aPath);  If aPath[i] = PathDelim then System.Dec(i);  While (i > 0) and (aPath[i] <> PathDelim) do system.dec(i);  If i = 0 then exit;  If (i = 1) and (aPath[i] = PathDelim) then exit;  Result := Copy(aPath, 1, i-1);End;                      //This function I pilfered from another site ...function IsValidFileName(AFileName: String): Boolean;const InvalidChars: set of AnsiChar = [#0..#31, '\', '/', ':', '*', '?', '"', '<', '>', '|'];      InvalidWords: array[0..21] of String = ('CON', 'PRN', 'AUX', 'NUL', 'COM1',       'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9', 'LPT1', 'LPT2',       'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9');var I, L, Lw: Integer;begin Result:= False; L:= Length(AFileName); if (L = 0) or (L > 255) or (AFileName[L] = '.') or (AFileName[L] = ' ') then Exit; for I:= 1 to L do  if (Ord(AFileName[I]) <= 255) and (AnsiChar(AFileName[I]) in InvalidChars) then Exit; AFileName:= UpperCase(AFileName); for I:= 0 to 21 do begin  Lw:= Length(InvalidWords[I]);  if (Pos(InvalidWords[I], AFileName) = 1) and   ((Lw = Length(AFileName)) or (AFileName[Lw+1] = '.')) then Exit; end; Result:= True;end; //This function checks that the path without the last folder exists and then checks that the //last folder exists or is syntactically correct.Function IsValidPath(aPath: String): Boolean;var LastDir: String;    PathToLastDir : String;    Drive: string;Begin   PathToLastDir := PathWithoutLastFolder(aPath);   Drive  := ExtractFileDrive(aPath);   Result := (PathToLastDir = '') or (PathToLastDir = Drive) or DirectoryExists(PathToLastDir);   If Not Result then exit;   LastDir := LastFolder(aPath);   Result := (LastDir = '') or IsValidFileName(LastDir);end; ---------------------------------------------------------------------- jamie · 2023-04-16 23:32 you are doing lots of excess work Look up Split. Its a helper for the String. MyString.Split returns an array of strings. There is the function by itself, I just can't remember the exact name atm. Also the OS has the GetDriveType api call where you can pass the string to it and it will return what it thinks. ---------------------------------------------------------------------- Kays · 2023-04-17 00:00 Quote from: EganSolo on April 17, 2023, 01:02:25 amHere's what I ended up doing. Would love it if you guys could show me how to improve on this code!It is mandatory to use the operating system’s assistance. You want to avoid a TOCTOU condition, i. e. the path appears valid when you check it, but the next moment it’s become invalid (e. g. because a path component was deleted in the meantime, or the privileges necessary have changed). You do that by opening a file descriptor. You could re-use the preexisting/implicit working directory for that. That means you immediately chDir to the (parent) directory the user specifies. If this fails, the path is invalid. If it succeeds, it’s valid, but – more importantly – it stays valid (at least for the process’ lifetime) because of the open file descriptor. (Some network file systems may not be reliable in that regard.) Quote from: EganSolo on April 16, 2023, 03:50:19 am[…] The reason is that the creation of the folder should take place once the user is ready to save the entire form. In case the user cancels, the folder should not be created. […]This is also subject to a potential TOCTOU condition. Someone else – a different user – might create the directory not granting you any access, so there’ll be an error eventually, too, even though everything appeared legit at first. You simply need to create the directory and delete it if the user cancels. Directories are cheap, so there’s no gain in postponing this step anyways. (Doing this you will observe a changed modification time though.) ---------------------------------------------------------------------- KodeZwerg · 2023-04-17 00:46 I do not really understand what you are actual trying to achieve, but when you want to be sure that a given path can and will be created, not re-invent the wheel and use ForceDirectories. If your app is getting a false back, than tell user to try again? QuoteForceDirectories tries to create any missing directories in Dir till the whole path in Dir exists. It returns True if Dir already existed or was created successfully. If it failed to create any of the parts, False is returned. ---------------------------------------------------------------------- 440bx · 2023-04-17 03:16 @EganSolo Your code tests for a filename "." but it's not just a dot that is illegal, any sequence of only dots is illegal.  IOW, a filename cannot be made of only one or more dots. The ":" is legal only as the second character Basically, your algorithm should first check that the filename (including path) is _structurally_ valid (e.g, no filenames made of only dots, colon appears only as the second character, etc.)  Once the structure is determined to be correct then the structural elements can be individually validated (e.g, the drive letter is valid, etc) I would also suggest _not_ trying to validate everything at once because it will make the code hard to maintain.  IOW, validate the structure first then, validate each structural element. HTH. ---------------------------------------------------------------------- Zvoni · 2023-04-17 08:34 On Windows (Only) there is "PathCleanupSpec" https://learn.microsoft.com/de-de/windows/win32/api/shlobj_core/nf- shlobj_core-pathcleanupspec?redirectedfrom=MSDN In a nutshell: Throw you String against that function (obey the rules as described), and it will tell you if any charactres have been replaced/removed (or whatever else) No idea about crossplatform ---------------------------------------------------------------------- EganSolo · 2023-04-18 17:30 @Jamie: Thanks for the tip about split. I'll be definitely using it in the future. @Kays: Excellent point about Toctu. I really appreciate your input. In my case, the app is a single user on a local desktop so the risk is somewhat mitigated but, to your point, the user could change the path outside the app. Initially, I thought the user could specify an entire fictitious path and therefore I would have to commit to creating the full path and if the user cancels, delete it. The trouble is only one part of the path was a valid path and the rest wasn't. I suspect that ForceDirectories would create the valid sub-path and would stop when it encounters an invalid folder name. In other words, I don't think ForceDirectories performs its work as a single unit of work. I am not aware of an equivalent function that would force delete a path until it encounters an invalid folder. Anyway, to make a long story short, once I restricted the ability of a user to operate from an existing path, your approach became easier to implement so thank you. @KodeZwerg: I'm familiar with ForceDirectories but the user could possibly cancel the form and the paths would be created for nothing. I don't want to create the paths unless the user commits first. @440bx: Excellent point! My code is not testing for these conditions. I would need to take that into consideration. In the end, I'll go with @Kay's approach. It's the safest and most sensical in my context. Thank you all for your input and suggestions! Much appreciate it.