How to search a file in the specified path? - vb6

I want to search a file from the path.
For Example,
Path = "C:\Newfolder\"
file name = *.txt, *.fin
I want to get all the *.txt, *.fin file from the new folder.

Use the Scripting.FileSystemObject.
Call it with GetFolder("C:\Newfolder"), then loop through the files in that folder with the
.Files property and filter them on extensions using the GetExtensionName method.
For example:
Dim fso as Object: Set fso = CreateObject("Scripting.FileSystemObject")
Dim f as Object
For Each f in fso.GetFolder("<folderpath>").Files
If fso.GetExtensionName(f.Path) = "txt" Then 'or maybe it's .txt, I'm not sure
' also test for 'fin'
'... do stuff
End If
Next f

Check out the Scripting.FileSystemObject.
In your project add a reference to the "Microsoft Scripting Runtime".
Then you can do something like this:
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
Dim fld As Scripting.Folder
Set fld = fso.GetFolder("d:\temp\newfolder")
Dim i As Integer
Dim ext As String
Dim fl As Scripting.File
For Each fl In fld.files
'get extension
ext = Mid(fl.Name, Len(fl.Name) - 2)
If ext = "txt" Or ext = "fin" Then
'do something with the file
End If
Next fl
This is one of the areas that got so much better with .NET.

Just drop-in a CDirDrill class that does it all for you, in full native VB6. Another excellent solution from Karl Peterson :)
The FileSystemObject is not recommended for a couple of reasons: one, it adds a dependency, and two, it depends on scripting, which may be disabled per policy. I've had bugs because some customer has managed to muck up scrrun.dll on their PC. Eliminate dependencies unless they're really helping you a lot.
BTW this question is a duplicate of this

Related

Find path with current user C:\users\%USERNAME%\... in .vbs

I won't to set objFolder path, but I can't get current username
objShell.NameSpace(C:\users\%CurrentUser%\AppData)
Code:
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace("C:\users\%USERNAME%\AppData\Roaming\Microsoft\Windows")
Or can I replace objShell.NameSpace("C:\somepath") different method?
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace("C:\users\%USERNAME%\AppData\Roaming\Microsoft\Windows")
If you are going to use Shell.Namespace you might want to read the documentation.
It says:
vDir [in]
Type: Variant
The folder for which to create the Folder object. This can be a string
that specifies the path of the folder or one of the
ShellSpecialFolderConstants values. Note that the constant names found
in ShellSpecialFolderConstants are available in Visual Basic, but not
in VBScript or JScript. In those cases, the numeric values must be
used in their place.
when you follow the link for ShellSpecialFolderConstants
You'll find
ssfSTARTMENU 0x0b (11). File system directory that contains Start menu
items. A typical path is C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu.
Which is I one level deeper than what you are looking for. So from that folder you can just go up one level and you have the folder you need.
Something like this should work:
option explicit
const ssfSTARTMENU = 11
sub main
msgbox getWindowsFolder().Self.Path
end sub
function getWindowsFolder()
dim shell
Set shell = CreateObject("Shell.Application")
dim startMenuFolder
set startMenuFolder = shell.Namespace(ssfSTARTMENU)
set getWindowsFolder = startMenuFolder.ParentFolder
end function
main

VB6 Dir("*.dot") globbing finding .dotx on one server but not the other

I have a very strange issue, that I hope someone else might know about.
I have a VB6 containing the following code
Dim filename As String: filename = Dir("c:\somepath\*.dot")
Do Until filename = ""
...add filename to listbox
filename = Dir()
loop
When I run the exact same program on one Windows Server 2012 R2 (call it Server A), Dir() will return only files ending on .dot.
On a different Windows Server 2012 R2 (Server B), Dir() will additionally return files ending on .dotx
Both servers have Microsoft Office 2013 Standard edition. Both servers have AFAICS the same settings in File Explorer.
Server A locale is English
Server B locale is Danish
Are there any registry settings, that could make file globbing behave like this? I am thinking specifically about DOTX being the new Office template format?
What you are seeing would occur if the creation of 8.3 file names were disabled on the file system of the machine that does not list the .docx files.
You can re-enable this feature using fsutil by reversing the instructions here.
I ran into a similar issue. Without being able to control the settings on every machine I ran my app on, it was easier to just deal with it in my code. I used FileSystemObject to iterate the files in the folder and compare the extension of the file to the extension I want to filter by. It was more reliable that filtering using Dir().
Public Sub ShowFileList(folderToSearch As String, extensionToFind As String)
Dim oFileSystemObject As New FileSystemObject
Dim oFiles As Files
Dim oFile As File
Dim fileName As String
Dim fileExtension As String
Set oFiles = oFileSystemObject.GetFolder(folderToSearch).Files
For Each oFile In oFiles
fileName = oFile.Name
fileExtension = oFileSystemObject.GetExtensionName(fileName)
If StrComp(fileExtension, extensionToFind, vbTextCompare) = 0 Then
Debug.Print fileName
End If
Next oFile
Set oFile = Nothing
Set oFiles = Nothing
Set oFileSystemObject = Nothing
End Sub
Private Sub Command1_Click()
ShowFileList "C:\MyFolder", "dot"
End Sub

Replace text within a file

Hello I've tried a lot of researching but cant find what I need and haven't been able to successfully piece this together myself.
Each of my users have a XML file within their profile that I would like to edit. The file contains a reference to their computer name and clientname, which are out of date each time they login to a new terminal. I need to replace these with the current computername and clientname. The bit I cannot figure out how to do is how to search the XML for the computername when I only know the first few characters, then replace it.
my XML will have any entry something like this
"InstalledPrinter name="\WHBCVDI0109\LabelPrinter650 (from IGEL-00E0C533943E)"
I need to search the file and replace the WHBCVDI0109 and the IGEL-00E0C533943E with the correct entries. My script successfully gets those entries I just dont know how to find and replace them in the file.
My script looks like this:
Const ForReading = 1
Const ForWriting = 2
Set oShell = CreateObject( "WScript.Shell" )
'Get Variables
user=oShell.ExpandEnvironmentStrings("%UserName%")
appdata=oShell.ExpandEnvironmentStrings("%appdata%")
strComputerName = oshell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )
'Set XML location
strfile = appdata & "\Smart Label Printer\SlpUserConfig.xml"
'Open
Set objfso = CreateObject("Scripting.FileSystemObject")
Set filetxt = objfso.OpenTextFile(strfile, ForWriting)
strTemp = "HKEY_LOCAL_MACHINE\SOFTWARE\Citrix\ICA\Session\ClientName"
WScript.Echo "client name is : " & oShell.RegRead(strTemp)
An pointers would be much appreciated.
You shouldn't use the FileSystemObject and String/RegExp operations to edit an XML file. Using the canonical tool - msxml2.domdocument - is less error prone and scales much better.
See here for an example (edit text); or here for another one (edit attribute).
If you publish (the relevant parts of) your .XML file, I'm willing to add same demo code specific for your use case here.

VB script - search for a file in directory

I am trying to write a VB script (having never attempted before) - I need it to search the folder'\file001\source$' - whilst in the folder search for all 'Update.exe'files - If this is done manually, in Windows it takes a long long time!
I would like all the files that it finds with this name - to be copied into a new folder.
Looking at various help forums I am getting more and more confused.
Below is what I have attempted:
Set fso = CreateObject("Scripting.FileSystemObject")
ShowSubfolders fso.GetFolder("\\file001\source$")
'foldername = "\file001\source$"
'filename = "Updater.exe"
Function ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Wscript.Echo Subfolder.Path
ShowSubFolders Subfolder
Next
End Function
This is to search through a folder, recursively through the folders sub folders to find all files with this name.
I have also done research into -directory.getfiles. But have no clue if this is the right direction.
As a newbie to VB script, I have researched and attempted to play around with vb script, to get the function I desire. I would be grateful to any help I can get.
Again - my target is to - find all files within the given folder and subfolders with the name update.exe - and then to copy these files found into a new folder.
Thank you in advance.
If you only want to check the content of a single folder for the existence of a particular file you can do that like this:
Set fso = CreateObject("Scripting.FileSystemObject")
foldername = "\\file001\source$"
filename = "Update.exe"
If fso.FileExists(fso.BuildPath(foldername, filename)) Then
WScript.Echo filename & " exists."
End If
If you want to check the subfolders of foldername as well, you need to recurse into subfolders with something like this. You can either integrate the check from the above code sample in the loop over the subfolders, or add another loop over the files in the folder:
Set fso = CreateObject("Scripting.FileSystemObject")
CopyUpdater fso.GetFolder("\\file001\source$")
Sub CopyUpdater(fldr)
For Each f In fldr.Files
If LCase(f.Name) = "update.exe" Then
'copy file to somewhere else
End If
Next
For Each sf In fldr.SubFolders
CopyUpdater sf
Next
End Sub
See my question here, i benchmark three languages (vbscript also) which do a subdirectory traversal with full working samples and optimised for the language. benchmarks: does python have a faster way of walking a network folder?
Thats a good attempt . Read more on below link and understand things better .
Vbscript list all PDF files in folder and subfolders
VBScript to traverse through subdirectories
dim sFilename
Dim objDict
Set objDict=CreateObject("Scripting.Dictionary")
sFilename = ""
'root folder path where subfolder exists
fileLocation="C:\Users\u258251\Desktop\TestSubfolder"
Dim objFSO 'File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Add all files with specific extention to dictonary
Call Recurse(fileLocation)
ItemArray = objDict.Items
'Loop through dictonary
For i = 0 To objDict.count -1
sFilename = sFilename & ItemArray(i) & VBCRLF
Next
msgbox(sFilename)
'find a specific file by name and return path
if objDict.Exists("DP103.txt") then
msgbox(objDict.Item("DP103.txt"))
end if
Sub Recurse(strFolderPath)
Dim objFolder
Set objFolder = objFSO.GetFolder(strFolderPath)
Dim objFile
Dim objSubFolder
For Each objFile In objFolder.Files
If (InStr(objFile.Name, ".") > 0) Then
'proceed if extention is .txt
If (LCase(Mid(objFile.Name, InStrRev(objFile.Name, "."))) = ".txt") Then
if objDict.Exists(objFile.Name)=false then
'add files and path to dictonary
objDict.Add objFile.Name,objfile.Path
End if
End if
End If
Next
For Each objSubFolder In objFolder.SubFolders
Call Recurse(objSubFolder.Path)
Next
End Sub

Rename and Move Folders Using VB

I have the following script which works great if I need to rename files in a folder but now I want to move and rename folders from one mapped drive to another mapped drive. Can someone help me to modify the script to do so? I am failry new to VB so pardon if I can't firgure this out but it took me a little while to figure this one out and now I am not sure how to modify this script. Thank you in advance!
The folders by default are labeled A.1234, A.5678, and so on and will always have a different number assigned to them. I will keep the numbers in the label as they are PO numbers. So my end result desired is Ack~1234, Ack~5678, and so on.
Dim fso, f, f1, fc, s Set
fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder("Y:\Test")
Set fc = f.Files
For Each f1 in fc
f1.move f1.ParentFolder & "\" & replace(f1.Name, "A.", "Ack~")
Again these folders exist on the root of a mapped drive and need to move to another mapped drive with the new names. If more info is needed please do not hesitate to ask.
UPDATE
I modified the script below to give an idea of what I'm looking to do.
Dim fso, objFol
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFol = fso.GetFolder("Z:\")
Set objFolders = objFol.Folders
For each folder in objFolders
fso.Movefolder folder, "Y:\" & Replace(fso.Name, "A.", "Ack~")
Next
This give me an error stating it does not support "Folder". There will be any number of folders in the Z drive and I need to move them all to the Y drive. Sorry if I didn't explain properly in the previous post.
The move command is taking a string, for which you're providing the parent folder of the file, so the file isn't moving. I think it'll be sufficient to provide a different folder location. For example:
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder("Y:\Test")
Set fc = f.Files
For Each f1 in fc
f1.move "Z:\TargetFolder\" & replace(f1.Name, "A.", "Ack~")
Note: I've not tested this, but if there are problems then just ask
Additional Stuff after update:
The following code will allow you to move folders, and do the replacements you need to the folder name string.
Dim fso, objFol, objMoveFol, strPathBuild
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFol = fso.GetFolder("Y:\Test")
For Each objMoveFol In objFol.SubFolders
'Replace the root folder locations in the path
strPathBuild = Replace(objMoveFol, "Y:\Test", "Z:\TargetFolder\")
'Do the required other fiddle
strPathBuild = Replace(strPathBuild, "A.", "Ack~")
fso.Movefolder objMoveFol, strPathBuild
Next
Make sure you're really careful with this sort of thing, as getting is wrong can be fairly spectacular.

Resources