Jump to content

Stripping the filename from a file path


Recommended Posts

I am embarassed to post this but i hate "jerry-rig's" and "quick fixes" especially when it comes to the script i am writing... that being said, here comes the humility...

I am trying to figure out how to take a filepath (example: C:\temp\blah\blah\blah\filename.txt) and return JUST the filename (example: filename.txt)...

failed to date:

;Spliting the path into an array

$patharray = StringSplit($filepath, "\")

;and try to use $patharray[0] to tell me which array variable to grab...

$counter = $patharray[0]

$filename = $patharray[' & $counter & ']

...

but when i try

MsgBox(4096, 'test variable', 'the filename is: ' & $filename)

it returns:

the filename is: 6

(which is obviously $patharray[0]).... but no errors.... (am i close?)

it was suggested at one point that i just build a psychotically big IF THEN ELSE friggin forrest for If $counter = '1' Then..... If $counter = '2' Then....

i'm sure there has got to be a better way to do this or i'm probably just forgetting something obvious... Any help you cats could throw me would be much appreciated

Link to comment
Share on other sites

Here's my version.

Func GetFilename($Path)
   Local $TempArr
   Local $Filename
   $TempArr = StringSplit($Path, "\")
   If @error Then
      $Filename = $Path
   Else
      $Filename = $TempArr[UBound($TempArr) - 1]
   EndIf
   Return $Filename
EndFunc
Link to comment
Share on other sites

you could use it and grab the working directory by removal as well:

$fullpath="c:\temp\bobs bilfold\notes\myprogram.exe"
$filename=GetFilename($fullpath)
$path=StringReplace($fullpath,$filename,"")
msgbox(1,$filename,$path)

Func GetFilename($Path)
  Local $TempArr
  Local $Filename
  $TempArr = StringSplit($Path, "\")
  If @error Then
     $Filename = $Path
  Else
     $Filename = $TempArr[UBound($TempArr) - 1]
  EndIf
  Return $Filename
EndFunc

I personally like the StringRight and StringLeft Approach:

$path=Splitit("c:\temp\bobs bilfold\notes\myprogram.exe")
msgbox(1,$path[0],$path[1])

func SplitIt($FPath); returns Path and file in array
Dim $patharray[2]
$_loc=StringInStr($FPath,"\",0,-1)
$patharray[0]=Stringright($FPath,StringLen($FPath)-$_loc)
$patharray[1]=Stringleft($FPath,$_loc)
return $patharray
endfunc

AutoIt3, the MACGYVER Pocket Knife for computers.

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...