Jump to content

_FileIsPathValid UDF


Shafayat
 Share

Recommended Posts

Function for checking if a File/Directory Path is Valid

#include-once
; #INDEX# =======================================================================================================================
; Title .........: _FileIsPathValid UDF
; AutoIt Version : 3.3.6+
; Language ......: English
; Description ...: Function for checking if a File/Directory Path is Valid
; Author(s) .....: Shafayat (sss13x@yahoo.com)
; ===============================================================================================================================

; #CURRENT# =====================================================================================================================
; _FileIsPathValid()
; ===============================================================================================================================

; #FUNCTION# ====================================================================================================================
; Name...........: _FileIsPathValid
; Description ...: checks if a File/Directory Path is Valid
; Syntax.........: _FileIsPathValid($Path, $Verbose = 0)
; Parameters ....: $Path - File/Directory Path to work with
;                  $Verbose  - OutPut (ConsoleWrite) additional information of invalidity of Path
;                  |0 - No OutPut
;                  |1 - OutPut to Console if Not Compiled
;                  |1 - OutPut to Console Always
; Return values .: Success - True
;                  Failure - False
; Author ........: Shafayat (sss13x@yahoo.com)
; Example .......: Yes
; ===============================================================================================================================

Func _FileIsPathValid($Path, $Verbose = 0)
    Local $PathOri = $Path
    Local $Excluded[8] = [7, "\\", "?", "*", '"', "<", ">", "|"] ;List of invalid characters
    Local $Alphabet = StringSplit("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "")
    Local $Reasons = ""
    Local $Valid = True
    ; Lenght Check
    If StringLen($Path) < 4 Then
        $Reasons = $Reasons & @CRLF & "LENGTH: Entire Pathname must be more than 3 characters (including drive)."
        $Valid = False
    EndIf
    ; Drive Check
    Local $pos = StringInStr($Path, ":\")
    If $pos <> 2 Then
        $Reasons = $Reasons & @CRLF & 'STRUCTURE: Drive letter must be one chars long and must be followed by ":\".'
        $Valid = False
    Else
        Local $chrdrv = StringUpper(StringLeft($Path, 1))
        Local $found = 0
        For $i = 0 To $Alphabet[0]
            If $chrdrv = $Alphabet[$i] Then
                $found = 1
            EndIf
        Next
        If $found = 0 Then
            $Reasons = $Reasons & @CRLF & "ILLEGAL CHARACTER: Illegal character used as drive letter."
            $Valid = False
        EndIf
    EndIf
    $Path = StringTrimLeft($Path, 3)
    ; Path + Name Check
    For $i = 0 To $Excluded[0]
        If StringInStr($Path, $Excluded[$i]) <> 0 Then
            $Reasons = $Reasons & @CRLF & "ILLEGAL CHARACTER: " & $Excluded[$i]
            $Valid = False
        EndIf
    Next

    If $Verbose = 2 And $Valid = False Then ConsoleWrite(@CRLF & "Invalid Path: " & $PathOri & $Reasons & @CRLF)
    If $Verbose = 1 And $Valid = False And @Compiled = False Then ConsoleWrite(@CRLF & "=============" & @CRLF & "Invalid Path: " & $PathOri & $Reasons & @CRLF)
    Return $Valid
EndFunc   ;==>_FileIsPathValid

Sample:

#include "_FileIsPathValid.au3"

$path = "d:\GooodBoy.au3"
MsgBox(0, $path, _FileIsPathValid($path, 1))

$path = "d:\Goo>odB\oo\oy.au3"
MsgBox(0, $path, _FileIsPathValid($path, 1))

$path = "jook:\Gooo*dBo\\?y.au3"
MsgBox(0, $path, _FileIsPathValid($path, 1))

$path = "sadasds?y.au3"
MsgBox(0, $path, _FileIsPathValid($path, 1))

_FileIsPathValid.zip

[Not using this account any more. Using "iShafayet" instead]

Link to comment
Share on other sites

Nice, but can be done using only RegExp:

$sPath = "D:\GooodBoy.au3"
$iPathIsValid = _FilePathIsValid($sPath)
ConsoleWrite($iPathIsValid & @LF)

$sPath = "D:\Not*GooodBoy.au3"
$iPathIsValid = _FilePathIsValid($sPath)
ConsoleWrite($iPathIsValid & @LF)

Func _FilePathIsValid($sPath)
    Local $sInvalid_Chars = '*?|:<>"/'
    Local $sPattern = '(?i)^[a-z]:([^\Q' & $sInvalid_Chars & '\E]+)?(\\[^\Q' & $sInvalid_Chars & '\E\\]+)?(\.[^\Q' & $sInvalid_Chars & '\E\\\.]+|\\)?$'
    Local $iPathIsValid = StringRegExp($sPath, $sPattern)
    
    Return $iPathIsValid
EndFunc

P.S

There is also my _FileGetValidName() UDF, wich will return the valid name.

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

And here is the same but returns the valid path as well (optional):

$sPath = "D:\GooodBoy.au3"
$iPathIsValid = _FilePathIsValid($sPath)
ConsoleWrite($iPathIsValid & @LF)

$sPath = "D:\Not*GooodBoy.au3"
$sPathValid = _FilePathIsValid($sPath, 1, '_')
ConsoleWrite("PathIsValid ==> " & @extended & @LF & "Valid Name  ==> " & $sPathValid & @LF)

Func _FilePathIsValid($sPath, $iRetValid = 0, $sReplaceChar = '')
    Local $sInvalid_Chars = '*?|:<>"/'
    Local $sPattern = '(?i)^([a-z]:\\?)([^\Q' & $sInvalid_Chars & '\E]+)?(\\[^\Q' & $sInvalid_Chars & '\E\\]+)?(\.[^\Q' & $sInvalid_Chars & '\E\\\.]+|\\)?$'
    Local $iPathIsValid = StringRegExp($sPath, $sPattern)
    
    If $iRetValid = 1 And Not $iPathIsValid Then
        Local $iLastCharIsSlash = (StringRight($sPath, 1) = '\')
        Local $aPathSplit = StringSplit(StringRegExpReplace($sPath, '\\+$', ''), '\')
        Local $sValidName
        
        $sPath = ''
        
        For $i = 2 To $aPathSplit[0] - 1
            $sValidName = StringRegExpReplace($aPathSplit[$i], '[\Q' & $sInvalid_Chars & '\E]', $sReplaceChar)
            
            If $sValidName <> '' Then
                $sPath &= $sValidName & '\'
            EndIf
        Next
        
        $sPath &= StringRegExpReplace($aPathSplit[$aPathSplit[0]], '[\Q' & $sInvalid_Chars & '\E]', $sReplaceChar)
        $sPath = StringLeft(StringRegExpReplace($aPathSplit[1], '[\Q' & $sInvalid_Chars & '\E]', $sReplaceChar), 1) & ':\' & $sPath
        
        If $iLastCharIsSlash Then
            $sPath &= '\'
        EndIf
        
        Return SetExtended(0, $sPath)
    EndIf
    
    Return $iPathIsValid
EndFunc

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Thank you for the regexp trick.

I am finally starting to get to understand regexp. :idea: But I'm not still fluent in it. I needed that functionality in my latest project so I scraped up it in the way I can think. :)

regards

Shafayat

[Not using this account any more. Using "iShafayet" instead]

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...