How to get a file name only from file's full path?
MY path - C:\Documents and Settings\Arshad\My Documents\ravi.txt
Have a look at this: Retrieve Filename without Path or Extension.
Here's the function from the above link:
Public Function GetFileName(flname As String) As String
'Get the filename without the path or extension.
'Input Values:
' flname - path and filename of file.
'Return Value:
' GetFileName - name of file without the extension.
Dim posn As Integer, i As Integer
Dim fName As String
posn = 0
'find the position of the last "\" character in filename
For i = 1 To Len(flname)
If (Mid(flname, i, 1) = "\") Then posn = i
Next i
'get filename without path
fName = Right(flname, Len(flname) - posn)
'get filename without extension
posn = InStr(fName, ".")
If posn <> 0 Then
fName = Left(fName, posn - 1)
End If
GetFileName = fName
End Function
When inputting
C:\Documents and Settings\Arshad\My Documents\ravi.txt
this function returns
ravi
The function is called as such:
Dim FileName As String
FileName = GetFileName("C:\Documents and Settings\Arshad\My Documents\ravi.txt")
This is the shortest way:
Public Function GetFileName(FilePath As String) As String
Dim l() as string
l=split(FilePath,"\")
GetFileName=l(UBound(l))
End Function
Tell me, if you can find shorter code;)
Here you go:
http://www.vbforums.com/showthread.php?t=475667
-
Here are the better and short way.
Return file name from FullPath
' ** C:\Windows\System32\calc.exe > Ret: calc.exe
Private Function GetFilenameFromPath(FullPath As String) As String
GetFilenameFromPath = Right(FullPath, Len(FullPath) - InStrRev(FullPath, "\"))
End Function
Return Path from FullPath
' C:\Windows\System32\calc.exe > Ret: C:\Windows\System32\
Private Function GetDirectoryFromPath(FullPath As String) As String
GetDirectoryFromPath = Left(FullPath, InStrRev(FullPath, "\"))
End Function
Related
I have an issue with the Dir function.
Private Sub InitFileElvt()
Dim fileName As String
Dim find As Boolean
Dim trouve As Boolean
trouve = False
fileName = Dir(THEORIQUE & "\" & LibPie & CftMot & _
Mid(NoPlan, 13, 1) & Mid(VERPIE, 1, 1) & "\") 'It works here
Do While fileName > "" And Not trouve
If IsElvtFile(fileName) Then
trouve = True
pathFileElvt = THEORIQUE & "\" & fileName
End If
fileName = Dir() 'An error here
Loop
If Not trouve Then
pathFileElvt = "empty"
End If
End Sub
Private Function IsElvtFile(ByVal fileName As String) As Boolean
Dim lengthDeb As Integer
lengthDeb = Len(LibPie) + Len(CftMot) + 1
IsElvtFile = Left(fileName, lengthDeb) = LibPie + CftMot + Mid(NoPlan, 13, 1) And _
Right(fileName, 4) = ".ELV"
End Function
The first call to Dir give me a file from the folder. Good. But the second call give me Run-Time Error '5': Invalid Procedure Call or Argument
What i'm missing about the Dir Function? Apparently, that's how it have to be used.
When i'm in debug mode, in the line Do While fileName > "" And Not trouve, my watch on dir returns the next file. After this line is executed, my watch shows the error.
There was other watch in Dir(otherPath)...
I've removed them and now it works
I need a way of natively calculate a MD5 HASH of a file in vbscript, and MD5 class has a property called GetMd5Hash which seems that can help me. I just have to read a file into a byte array and then apply this method. I found a script code in web page
http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2 which is exactly what I need but when I run it with command cscript /E:vbs md5.vbs if fails with error code:
md5.vbs(7,5) Microsoft VBScript compilation error: Syntax error. Can someone help me solve this error please?
The code is:
Imports System
Imports System.Security.Cryptography
Imports System.Text
Class Program
Shared Sub Main(ByVal args() As String)
Dim [source] As String = "Hello World!"
Using md5Hash As MD5 = MD5.Create()
Dim hash As String = GetMd5Hash(md5Hash, source)
Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".")
Console.WriteLine("Verifying the hash...")
If VerifyMd5Hash(md5Hash, [source], hash) Then
Console.WriteLine("The hashes are the same.")
Else
Console.WriteLine("The hashes are not same.")
End If
End Using
End Sub 'Main
Shared Function GetMd5Hash(ByVal md5Hash As MD5, ByVal input As String) As String
' Convert the input string to a byte array and compute the hash.
Dim data As Byte() = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input))
' Create a new Stringbuilder to collect the bytes
' and create a string.
Dim sBuilder As New StringBuilder()
' Loop through each byte of the hashed data
' and format each one as a hexadecimal string.
Dim i As Integer
For i = 0 To data.Length - 1
sBuilder.Append(data(i).ToString("x2"))
Next i
' Return the hexadecimal string.
Return sBuilder.ToString()
End Function 'GetMd5Hash
' Verify a hash against a string.
Shared Function VerifyMd5Hash(ByVal md5Hash As MD5, ByVal input As String, ByVal hash As String) As Boolean
' Hash the input.
Dim hashOfInput As String = GetMd5Hash(md5Hash, input)
' Create a StringComparer an compare the hashes.
Dim comparer As StringComparer = StringComparer.OrdinalIgnoreCase
If 0 = comparer.Compare(hashOfInput, hash) Then
Return True
Else
Return False
End If
End Function 'VerifyMd5Hash
End Class 'Program
' This code example produces the following output:
'
' The MD5 hash of Hello World! is: ed076287532e86365e841e92bfc50d8c.
' Verifying the hash...
' The hashes are the same.
This md5_of_file.vbs works for me (tested on Win10 Ent N):
' md5_of_file.vbs - Prints md5 hashes of specified files
' Combined at least from following sources:
' md5 from https://stackoverflow.com/a/31453654
' https://support.microsoft.com/en-us/help/276488/how-to-use-the-adodb-stream-object-to-send-binary-files-to-the-browser
Dim md5obj
set md5obj = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")
md5obj.Initialize()
Set fso = CreateObject("Scripting.FileSystemObject")
Const adTypeBinary = 1
Set objStream = CreateObject("ADODB.Stream")
Function bytesToHex(aBytes)
Dim hexStr, x
For x=1 To lenb(aBytes)
hexStr= LCase(hex(ascb(midb( (aBytes) ,x,1))))
if len(hexStr)=1 then hexStr="0" & hexStr
bytesToHex=bytesToHex & hexStr
Next
end Function
' read bytes from fileName
Function LoadFile(fileName)
objStream.Open
objStream.Type = adTypeBinary
objStream.LoadFromFile( fileName )
LoadFile = objStream.Read
objStream.Close
End Function
' returns hex value of md5 hash from content of fileName
Function HashOfFile(fileName)
fileBytes = LoadFile(fileName)
' Do NOT omit braces around fileBytes - it will not work...
md5hashBytes = md5obj.ComputeHash_2( (fileBytes) )
HashOfFile = bytesToHex(md5hashBytes)
End Function
If WScript.Arguments.Count < 1 Then
WScript.Echo("Script to compute md5 hash of specified files...")
WScript.Echo("Usage: " & WScript.ScriptName & " file1 ...")
WScript.Quit(1)
End If
For i = 0 To Wscript.Arguments.Count-1
fileName = WScript.Arguments.Item(i)
WScript.Echo( HashOfFile(fileName) & " " & fileName )
Next
Example usage from cmd:
cscript //nologo md5_of_file.vbs c:\windows\explorer.exe
e4a81eddff8b844d85c8b45354e4144e c:\windows\explorer.exe
Copyright disclaimer - most code comes from https://stackoverflow.com/a/31453654
Get Microsoft's File Checksum Integrity Verifier for md5/sha1 code, it's command line mode and very fast. Just extract it to System32 folder.
If I have the full path of a file:
eg. c:\files\file.txt
What would be the easiest way to get the folder of this file: eg. c:\files\ ?
Use FileSystemObject.GetParentFolderName(strFullFilePath) e.g.
Dim strFullFilePath As String
strFullFilePath = "c:\files\file.txt"
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
MsgBox fso.GetParentFolderName(strFullFilePath)
Note this returns c:\file rather than c:\file\
You can use InStrRev for searching for the \, and Left$ for extracting the path bit:
filename = "c:\files\file.txt"
posn = InStrRev(filename, "\")
If posn > 0 Then
pathstr = Left$(filename, posn)
Else
pathstr = ""
End If
I'd make a function out of it for ease of use:
Function pathOfFile(fileName As String) As String
Dim posn As Integer
posn = InStrRev(fileName, "\")
If posn > 0 Then
pathOfFile = Left$(filename, posn)
Else
pathOfFile = ""
End If
End Function
' GetFilenameWithoutExtension: Return filename without extension from complete path
Public Function GetFilenameWithoutExtension(path As String) As String
Dim pos As Integer
Dim filename As String
pos = InStrRev(path, "\")
If pos > 0 Then
filename = Mid$(path, pos + 1, Len(path))
GetFilenameWithoutExtension = Left(filename, Len(filename) - Len(Mid$(filename, InStrRev(filename, "."), Len(filename))))
Else
GetFilenameWithoutExtension = ""
End If
End Function
' GetFilenameWithExtension: Return filename with extension from complete path
Public Function GetFilenameWithExtension(path As String) As String
Dim pos As Integer
pos = InStrRev(path, "\")
If pos > 0 Then
GetFilenameWithExtension = Mid$(path, pos + 1, Len(path))
Else
GetFilenameWithExtension = ""
End If
End Function
' GetDirectoryFromPathFilename: Return directory path contain filename
Public Function GetDirectoryFromPathFilename(path As String) As String
Dim pos As Integer
pos = InStrRev(path, "\")
If pos > 0 Then
GetDirectoryFromPathFilename = Left$(path, pos)
Else
GetDirectoryFromPathFilename = ""
End If
End Function
Using VB6
Code.
Dim posn As Integer, i As Integer
Dim fName As String
posn = 0
For i = 1 To Len(flname)
If (Mid(flname, i, 1) = "\") Then posn = i
Next i
fName = Right(flname, Len(flname) - posn)
posn = InStr(fName, ".")
If posn <> 0 Then
fName = Left(fName, posn - 1)
End If
GetFileName = fName
FileName: Clockings8.mis06042009 120442.fin
But it is showing a filename is “Clockings8”. It should show “Clockings8.mis06042009 120442”
How to modify a code?
Need vb6 code Help
It is a bit cleaner to use the Scripting.FileSystemObject component. Try:
Dim fso as New Scripting.FileSystemObject
GetFileName = fso.GetBaseName(fname)
The reason why your code stops short is that InStr works from the beginning of the string to the end and stops wherever it finds a match. The filename "Clockings8.mis06042009 120442.fin" contains two periods. For this reason, you should use InStrRev instead to start the search from the end of the string.
Going with FileSystemObject's GetBaseName like David suggests is a good idea. If you can't or don't want to (and there are reasons why you might not want to) work with the FileSystemObject there's a simple solution: Remove all characters from a filename string starting with the last dot in the name.
Here's what I mean:
Dim fn As String
fn = "Clockings8.mis06042009 120442.fin"
Dim idx As Integer
idx = InStrRev(fn, ".")
GetFileName = Mid(fn, 1, idx - 1)
If your filename does not have an extenstion but has a dot somewhere in the filename string, then this method will return bad results.
Using VB6
I want to delete the last 5 words of the filename, then i want to give so other filename.\
Code.
Name FileName As NewFileName
The above code is working for rename, but i don't want to rename, i want to delete the last 5 letter of the filename.
Expected Output
Filename
sufeshcdk.txt - I want to take (sufeshcd) only
Modifyulla.txt - I want to take (Modifyul) only
How to do this?
Need VB6 Code Help.
Here you go.
private function RemoveLast5(FileName as string) as String
if len(FileName) > 5 then
RemoveLast5 = left$(FileName, Len(FileName) - 5)
else
RemoveLast5 = FileName
end
end function
dim FileName as string
FileName = "Modifyulla.txt"
dim NewFileName as string
NewFileName = RemoveLast5(FileName)
Name FileName As NewFileName
Untested, but this is the basic idea...
FileNameLength = Len(FileName)
NewFileName = Mid$(FileName, 1, FileNameLength - 5)
Name FileName As NewFileName
edit: fixed the syntax per below comments.