search jpg file name in folders and subfolders and copy result file names - directory

I am trying to get all the jpg file names related to 1 product. e.g. this is the product name 37004378_TM search this in file explorer & copy all the result file names like
37004378_TM-99999999_01.jpg 37004378_TM.jpg 37004378_TM_B.jpg 37004378_TM_B3.jpg 37004378_TM_D1.jpg 37004378_TM_D2.jpg 37004378_TM_D3.jpg 37004378_TM_D4.jpg 37004378_TM_D5.jpg 37004378_TM_D8.jpg
Tried a lot of things and already.
Sub jec()
Dim xp As String, a As Variant
dim TargetAddress as string
xp = "C:\Users\xxxx\Documents\37004378_TM*.jpg"
TargetAddress = activecell.value
xp = "C:\Users\xxxx\Documents\TargetAddress*.jpg"
a = Split(CreateObject("wscript.shell").exec("cmd /c dir """ & xp & """ /b/s").stdout.readall, vbCrLf)
Cells(1).Resize(UBound(a)) = Application.Transpose(a)
End Sub
I tried this it's very slow and I have a list 150 images. It's not working with variable

Related

Count all files in folder and subfolder with VB6

In VB6, I am using a Webbrowser form to display all files and subfolders as icons in the style of Windows Explorer. On the form, I display a count of all files in the main folder and all subfolders. This is my code so far, though haven't been able to find any information about counting subfolders.
Private Sub Load_Form()
Dim myPathName as String
Dim iTotalCount as Long
some stuff here ....
WebBrowser1.Navigate myPathName
WebBrowser1.Document.CurrentViewMode = 5 'medium icons
iTotalCount = FileCount(myPathName)
lblLabel.Caption = "Total Files = " & iTotalCount
more stuff here ....
End Sub
Public Function FileCount(myPathName as String) as Long
Dim FSO as New FileSystemObject
Dim fld as Folder
If FSO.FolderExists(myPathName) Then
Set fld = FSO.GetFolder(myPathName)
FileCount = fld.Files.Count
End If
End Function
This StackOverFlow question is similar, though for vb.net (which I don't know). I'd appreciate someone pointing me in the right direction. Many thanks.

Get only part of file name and delete from server folder in asp.net vb

I'm trying get get only the last part of a file name in a server folder between the "_" and ".pdf" in order to delete specific files only.
The files in the invoices folder are like this: Invoice_12345.pdf, Invoice_2345.pdf, Invoice_5555.pdf, etc. I need to extract the "12345", "2345", and "5555", then I need to delete the file if it is not contained in a database query.
With the following code, I wish to extract the digits from the files in the folder, so how do I get the number between "_" and ".pdf"?
Dim files() As String = Directory.GetFiles(Server.MapPath("/Contents/Invoices/"))
For Each file As String In files
list.Add(file)
Next
Then I need to delete the file from the server if the extracted number is not contained in a dataset I query from the database, but maybe that is a question for a different post.
For example, for Invoice "5555"
If PaidFull = True
File.Delete(file)
End If
Of course, I would have to then get the full file name to delete if from the server at that point.
This is a way to get only the numbers :
For Each file As String In files
Dim the_number As String = Path.GetFileNameWithoutExtension(file)
the_number = the_number.Substring(the_number.LastIndexOf("_") + 1, the_number.Length - the_number.LastIndexOf("_") - 1)
list.Add(the_number )
Next
Or with Regex (ty to Jimi) :
dim the_number = Regex.Match(file, "_(\d+)\.").Groups(1).Value
You really don't need to mess with parsing the file name if you are sure the number won't pop up somewhere in the directory path.
'Dim list = Directory.GetFiles("C:\SomeDirectory").ToList
Dim myTestList As New List(Of String) From {"Invoice_12345.pdf", "Invoice_2345.pdf", "Invoice_5555.pdf"}
For Each fileName In myTestList
If fileName.Contains("5555") Then
Debug.Print(fileName) 'Or do what you need to do
End If
Next

Rename file name based on upload date

I write the below code to copy the file and rename file name but the problem that i have now that i need to pick the last file (based on upload date) then rename the file , the below code change all files placed in the folder regardless the upload date , also if there is a simple code to upload file check if file is exist then show message (successful upload , failed upload (duplicate file))
Dim directory = Server.MapPath("App_Data/text/")
For Each filename As String In IO.Directory.GetFiles(directory, "*", IO.SearchOption.AllDirectories)
Dim fName As String = IO.Path.GetFileName(filename)
If fName.ToString Like "*Cust*" Then
System.IO.File.Delete(Server.MapPath("App_Data\test\Customer.txt"))
My.Computer.FileSystem.CopyFile(Server.MapPath("App_Data\text\" & fName), Server.MapPath("App_Data\test\" & fName))
My.Computer.FileSystem.RenameFile(Server.MapPath("App_Data\test\" & fName), "Customer.txt")
you can use below code and find creation date and last modified date of a file:
Dim creation as DateTime = File.GetCreationTime(#"C:\test.txt")
Dim modification as DateTime = File.GetLastWriteTime(#"C:\test.txt")
or by Importing System.IO and using this code:
Dim fi as FileInfo = new FileInfo("path")
Dim created = fi.CreationTime
Dim lastmodified = fi.LastWriteTime
i think the second one is better because you can put them in a collection easily and then sort them or compare them.

copy media files from one folder to another, but rename the files

I want to have a function in my game manager that "clones" a game. So far I have all the cloning working except cloning the game media.
I want the media to clone/copy like this:
basePath + gameId + mediaFile
So a simple example would look like this:
--- original game
c:\inetpub\wwwroot\spac_rpg\MediaFiles\12\33d43636-275b-4b92-8778-cf591829103e.png
c:\inetpub\wwwroot\spac_rpg\MediaFiles\12\57ea0ad8-c69a-45e7-951e-d0325aa404ab.mov
becomes
--- new clone of the game (notice the different gameIds and the different GUID Ids for the media)
c:\inetpub\wwwroot\spac_rpg\MediaFiles\13\4427a554-b6a7-457a-b5ff-7c7cb7aee5bb.png
c:\inetpub\wwwroot\spac_rpg\MediaFiles\13\e9371c5d-eb47-4014-8380-204f7aff44fb.mov
So far I have this, which isn't much, but I'm kinda stuck on where to go next:
' copy each media file to new folder with new name
' new and old media file IDs
Dim newMediaId As Guid
Dim oldMediaId As Guid
Dim oldGameId As Int
' base path for game media
Dim basePath = "C:\inetpub\wwwroot\spac_rpg\MediaFiles\"
' new media folder
Dim newMediaFolder = Directory.CreateDirectory(basePath & newGameId)
' XXX ds is a dataset that is returned from the database with the old and new mediaIDs
For Each dr As DataRow In ds.Tables(0).Rows
oldMediaId = dr("oldMediaID")
newMediaId = dr("newMediaID")
Dim oldFile = (basePath & oldGameId & "\" & oldMediaId)
Dim clonedFile = (basePath & newGameId & "\" & newMediaId)
Next
Or maybe I'm trying to break this down to much and there's a much easier way of copying?
I just need to make sure that the new folder with the new GameId is created and that each new media file is cloned with the newMediaId that is returned from the database call.
Thanks!
The System.IO.File.​Copy can do the copy for you. It takes the source file and destination file (which can be different) as parameters).
System.IO.File.​Copy(oldFile, clonedFile)

Listing a folder structure in Classic ASP

I've developed a secure page in ASP for the company I work for. There is a landing (login page) that once you are authenticated you are taken to a page that has links to several sub pages. Each sub page has a folder structure. For example: There is a heading for Meeting Minutes and then underneath and indented are links referencing PDFs that contain the information. There may be 3 or 4 headings with documents linked beneath.
The original version had a PHP script that ran and would sync up the live site on the server from a folder structure that would be mimicked onto the live site. So if I had a folder called Folder1 and sub folders named test1 test2 test3.. the live site would display them accordingly. Since the site is now in ASP and not PHP.. the PHP script no longer works (since PHP doesn't play well with ASP).
I found a snippet online that somewhat works for what i'm trying to achieve (i.e. Folder/Subfolder/File Name structure), however i'm stuck at the moment with how to link the files so they open when clicked. I keep seeing a %25 in the file name. I know %20 is the same as a blank space and since I am dealing with file and folder names that contain spaces, this appears to be my issue. I've tried adding in a %20 but the spaces become "%2520".
If you look at the code below, there is a link towards the bottom that calls "MapURL". I have that link commented out at the moment as I was trying to figure out where the %25 was coming from.
Anyone have any thoughts on how to get the links to work?
Here is the snippet.
dim path
path = "PATH TO THE FOLDER ON THE SERVER"
ListFolderContents(path)
sub ListFolderContents(path)
dim fs, folder, file, item, url
set fs = CreateObject("Scripting.FileSystemObject")
set folder = fs.GetFolder(path)
'Display the target folder and info.
Response.Write("<ul><b>" & folder.Name & "</b>") '- " _
' & folder.Files.Count & " files, ")
'if folder.SubFolders.Count > 0 then
' Response.Write(folder.SubFolders.Count & " directories, ")
'end if
'Response.Write(Round(folder.Size / 1024) & " KB total." _
' & "</ul>" & vbCrLf)
Response.Write("<ul>" & vbCrLf)
'Display a list of sub folders.
for each item in folder.SubFolders
ListFolderContents(item)
next
'Display a list of files.
for each item in folder.Files
'url = MapURL(item.path)
'Response.Write("<li>" & item.Name & " - " _
Response.Write("<li>" & item.Name & " - " _
& item.Name & "</a>" _
& "</li>" & vbCrLf)
next
Response.Write("</ul>" & vbCrLf)
Response.Write("</ul>" & vbCrLf)
end sub
function MapURL(path)
dim rootPath, url
'Convert a physical file path to a URL for hypertext links.
rootPath = Server.MapPath("/")
url = Right(path, Len(path) - Len(rootPath))
MapURL = Replace(url, "\", "/")
end function
There are several things wrong with your code.
First and foremost, you do not encode the values you output at all. This is a big mistake. You are missing URL-encoding for things that go into the HREF attribute, and you miss HTML-encoding for everything else.
Next, you create a new FileSystemObject with every call to the recursive ListFolderContents() function. This is unnecessarily wasteful and will become slow as soon as there are more than a handful of files to be output.
Your recursive function should take a Folder object as the first argument, not a path. This makes things a lot easier.
The HTML structure you output is invalid. <b> cannot legally be a child of <ul>.
I completely rewrote your code to produce more correct output and to be as fast as possible. Crucial to your problem is the PathEncode() function, it transforms a relative path to a properly encoded URL. The other things should be pretty self-explanatory:
ListFolder "P:\ATH\TO\THE\FOLDER\ON\THE\SERVER"
' -- Main Functions ----------------------------------------------------
Sub ListFolder(path)
Dim fs, rootPath
Set fs = CreateObject("Scripting.FileSystemObject")
rootPath = Replace(path, Server.MapPath("/"), "") & "\"
ListFolderContents fs.GetFolder(path), PathEncode(rootPath)
End Sub
' ----------------------------------------------------------------------
Sub ListFolderContents(folder, relativePath)
Dim child
Say "<ul>"
Say "<li><div class=""folder"">" & h(folder.Name) & "</div>"
For Each child In folder.SubFolders
If Not IsHidden(child) Then
ListFolderContents child, relativePath & PathEncode(child.Name) & "/"
End If
Next
relativePath = h(relativePath)
For Each child In folder.Files
If Not IsHidden(child) Then
Say "<li>" & h(child.Name) & "</li>"
End If
Next
Say "</ul>"
End Sub
' -- Helper Functions / Shorthands ---------------------------------------
Sub Say(s)
Response.Write s & vbNewLine
End Sub
Function h(s)
h = Server.HTMLEncode(s)
End Function
Function PathEncode(s)
' this creates a more correct variant of what Server.URLEncode would do
PathEncode = Replace(s, "\", "/")
PathEncode = Server.URLEncode(PathEncode)
PathEncode = Replace(PathEncode, "+", "%20")
PathEncode = Replace(PathEncode, "%2F", "/")
PathEncode = Replace(PathEncode, "%2E", ".")
PathEncode = Replace(PathEncode, "%5F", "_")
End Function
Function IsHidden(File)
IsHidden = File.Attributes And 2 = 2
End Function
Notes
Use the <div class="folder"> to apply CSS styles (i.e. bold etc.) to the folder name.
The function will not output hidden files or directories.
The relativePath argument is used to keep the workload as low as possible - when a folder has 1000 files, it makes no sense to calculate the entire relative path 1000 times. With the help of this parameter, only the part that actually changes is processed.
Having functions like Say() or h() around can save you a lot of typing and it keeps the code more clean, too.
You should read up on URL-encoding (and HTML-encoding as well). Seems like you've never come across these things, which is especially bad if your task is to build a secure site.
you probably need extra quotes at the href (""). The best way is to see the generated source code (from the resulting page) like <a href=""" & replace(...) & """>"
Basically, if you use only one quote it just closes the string, but you are missing the HTML quote needed after href= and the closing one.

Resources