Copy a file from one folder to another by matching a string in a file name and rename the copied file by appending date and time to the file name - vb.net

I need to copy my server log file to another folder up on completion of one log file and then rename the copied file adding date and time to the file name.
Source : C:\Server\Logs
Destination : Can be selected by user using .BrowseForFolder
Log file name : Server_log_23.txt ("23" is the log number which will change from 1 to 30)
One log file will be completed in 2 minutes and log writing will be moved to next file by adding one (that means if Server_log_23.txt is completed then server will starts writing logs in Server_logs_24.txt till Server_log_30.txt, if log_30 is completed then it will starts writing in log_1)

I got a code like this, but it is not giving a continuous loop
Const DestinationFile = "C:\Users\Testbench\Desktop\file copy\Destination\"
Const src = "C:\Users\Testbench\Desktop\file copy\Source\"
strInput = UserInput( "Please enter file number:" )
strInput1 = "log_(" &strInput1 &")"
Dim sDateTimeStamp
Dim folder
Sub CopyFile()`enter code here`
Set fso = CreateObject("Scripting.FileSystemObject")
srcfile = strInput
Set folder = fso.GetFolder(src)
For Each file In folder.files
If instr(file.name, strInput) > 0 Then
srcfile=file.name
WScript.Echo srcfile
End If
Next
SourceFile= "C:\Users\Testbench\Desktop\file copy\Source\" & srcfile
WScript.Echo SourceFile
sDateTimeStamp = cStr(Year(now())) & _
Pad(cStr(Month(now())),2) & _
Pad(cStr(Day(now())),2) & _
Pad(cStr(Hour(now())),2) & _
Pad(cStr(Minute(now())),2) & _
Pad(cStr(Second(now())),2)
WScript.Echo "Copying " & SourceFile & " to " & DestinationFile
fso.CopyFile SourceFile, DestinationFile & srcfile & "_" & sDateTimeStamp & ".txt", True
Set fso = Nothing
End Sub
Function Pad(CStr2Pad, ReqStrLen)
Dim Num2Pad
Pad = CStr2Pad
If len(CStr2Pad) < ReqStrLen Then
Num2Pad = String((ReqStrlen - Len(CStr2Pad)), "0")
Pad = Num2Pad & CStr2Pad
End If
End Function
Function UserInput( myPrompt )
If UCase( Right( WScript.FullName, 12 ) ) = "\CSCRIPT.EXE" Then
WScript.StdOut.Write myPrompt & " "
UserInput = WScript.StdIn.ReadLine
Else
UserInput = InputBox( myPrompt )
End If
End Function
Do while strInput1<30
wscript.sleep 180
CopyFile()
strInput1 = strInput1 + 1
Exit Do
strInput1 =1
CopyFile()
strInput1 = strInput1 + 1
Loop

Related

Copy a file to a folder created with a table field as part of the name

I found some VBA routines here in and I tried to adapt them to my situation.
It works fine but when I try to copy a file to a folder that has been created using in its name a constant “process” and a variable [ID] field, I get an error message.
The error is in this line
FileCopy f.SelectedItems(i), "O:\docs\process\ " & (me.ID)
Private Sub Comando356_Click()
' lets say my current record has an ID field value 345
' The routine will check if folder O:\docs\process345 exists
' If the folder does not exist, then the folder is created:
If
Len(Dir("O:\docs\process" & (Me.ID), vbDirectory)) = 0 Then
MkDir "O:\docs\process" & (Me.ID)
End If
‘ So far it works perfectly: if the folder does not exist, is created
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
If f.Show Then
For i = 1 To f.SelectedItems.Count
sFile = Filename(f.SelectedItems(i), sPath)
' My problem is the next line: folder O:\docs\process345 exists but I get an error 76 “Path not Found”
FileCopy f.SelectedItems(i), "O:\docs\process" & (me.ID)
Next
End If
End Sub
Public Function Filename(ByVal strPath As String, sPath) As String
sPath = Left(strPath, InStrRev(strPath, "\"))
Filename = Mid(strPath, InStrRev(strPath, "\") + 1)
End Function
add a Slash and add the FileName
Private Sub Comando356_Click()
' lets say my current record has an ID field value 345
' The routine will check if folder O:\docs\process345 exists
' If the folder does not exist, then the folder is created:
If
Len(Dir("O:\docs\process" & (Me.ID), vbDirectory)) = 0 Then
MkDir "O:\docs\process" & (Me.ID)
End If
‘ So far it works perfectly: if the folder does not exist, is created
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
If f.Show Then
For i = 1 To f.SelectedItems.Count
sFile = Filename(f.SelectedItems(i), sPath)
' My problem is the next line: folder O:\docs\process345 exists but I get an error 76 “Path not Found”
' add some debugging
Debug.Print ("in=" & f.SelectedItems(i) & " out=" & "O:\docs\process" & (me.ID) & "\" & sFile)
' add a Slash and add the FileName
FileCopy f.SelectedItems(i), "O:\docs\process" & (me.ID) & "\" & sFile ' <<<<
Next
End If
End Sub
Public Function Filename(ByVal strPath As String, sPath) As String
sPath = Left(strPath, InStrRev(strPath, "\"))
Filename = Mid(strPath, InStrRev(strPath, "\") + 1)
End Function

Sorting filenames by conditions

I want to create a bit of code that saves a file out to a folder (PDF / DWG ) and moves all my files with a lower revision #5 than the current file being saved into a superseded folder.
I cannot see how to set a condition for the revision number: I can't use a wildcard as that would cause issues as other files in the folder would be picked up and moved incorrectly.
I have the save function sorted, I just dont know were to start with filing part.
Examples of the filenames:
Pdf/TE1801_200-01_{name}_#5.PDF
Dwg/TE1801_200-01_{name}_#5.DWG
You could use the GetBaseName Method to get just the filename without the extension
Then use the INSTRREV Function to find the position of the last "#" (just in case someone used a "#" in the {name} part).
Next use the LEFT Function to get the the "TE1801_200-01_{name}_#" part and now you can add a wildcard to it like "TE1801_200-01_{name}_#*.*". (It doesn't matter whether or not you have the "#" at the end at this stage.)
Prepend the full path and get all the matching files.
Move those files.
Now save the current file with its revison number.
' ------------------------------------------------------------------------------
' MOVE OLD REVISION TO SUPERSEDED FOLDERS - PDF
' ------------------------------------------------------------------------------
URLPASS = Filepath & "PDF\"
Dim MyObj As Object, MySource As Object, file As Variant
Set MyObject = CreateObject("Scripting.FileSystemObject")
Set MySource = MyObject.GetFolder(URLPASS)
For Each file_ In MySource.Files
LArray = Split(file_, "#")
checkfile = LArray(0)
REV = Split(LArray(1), ".")
If LArray(0) = checkfile And REV(0) < VERSION Then
' FILE FORMATING
' ----------------------------------------
RECON = Split(file_, "PDF\")
file_ = RECON(1)
RECON = Split(file_, ".")
DRAWNOCONFIG = RECON(0)
' MOVE TO NEW LOCATION
' ----------------------------------------
If Dir(Filepath & "PDF" & "\SUPERSEDED", vbDirectory) = "" Then '
MkDir Filepath & "PDF" & "\SUPERSEDED"
End If
Name Filepath & "PDF\" & DRAWNOCONFIG & ".pdf" As Filepath & "PDF\" & "SUPERSEDED\" & DRAWNOCONFIG & ".pdf"
Else
'DO NOTHING
GoTo Endline
End If
Endline:
Next file_
' ------------------------------------------------------------------------------
' MOVE OLD REVISION TO SUPERSEDED FOLDERS - DWG
' ------------------------------------------------------------------------------
URLPASS = Filepath & "DWG\"
Set MyObject = CreateObject("Scripting.FileSystemObject")
Set MySource = MyObject.GetFolder(URLPASS)
For Each file_ In MySource.Files
LArray = Split(file_, "#")
checkfile = LArray(0)
REV = Split(LArray(1), ".")
If LArray(0) = checkfile And REV(0) < VERSION Then
' FILE FORMATING
' ----------------------------------------
RECON = Split(file_, "DWG\")
file_ = RECON(1)
RECON = Split(file_, ".")
DRAWNOCONFIG = RECON(0)
' MOVE TO NEW LOCATION
' ----------------------------------------
If Dir(Filepath & "DWG" & "\SUPERSEDED", vbDirectory) = "" Then '
MkDir Filepath & "DWG" & "\SUPERSEDED"
End If
Name Filepath & "DWG\" & DRAWNOCONFIG & ".dwg" As Filepath & "DWG\" & "SUPERSEDED\" & DRAWNOCONFIG & ".dwg"
Else
'DO NOTHING
GoTo Endline2
End If
Endline2:
Next file_

Error while Uploading Multiple files

Hi when I was trying to upload files it shows the path is not virtual it shows with "E:/"+dest path so can anyone suggest how to upload my file in dest path below is the VB code
Protected Sub Upload_Files(sender As Object, e As EventArgs)
' CHECK IF ANY FILE HAS BEEN SELECTED.
If fileUpload.HasFile Then
Dim iUploadedCnt As Integer = 0
Dim iFailedCnt As Integer = 0
Dim hfc As HttpFileCollection = Request.Files
lblFileList.Text = "Select <b>" & hfc.Count & "</b> file(s)"
If hfc.Count <= 10 Then ' 10 FILES RESTRICTION.
For i As Integer = 0 To hfc.Count - 1
Dim hpf As HttpPostedFile = hfc(i)
If hpf.ContentLength > 0 Then
If Not File.Exists(Server.MapPath("\\Destinationpath\testing") & _
Path.GetFileName(hpf.FileName)) Then
Dim objDir As New DirectoryInfo(Server.MapPath("\\Destinationpath\testing"))
Dim objFI As FileInfo() = _
objDir.GetFiles(Replace(Path.GetFileName(hpf.FileName), _
Path.GetExtension(hpf.FileName), "") & ".*")
If objFI.Length > 0 Then
' CHECK IF FILE WITH SAME NAME EXISTS (IGNORING THE EXTENTIONS).
For Each file As FileInfo In objFI
If Replace(objFI(0).Name, Path.GetExtension(objFI(0).Name), "") = _
Replace(Path.GetFileName(hpf.FileName),
Path.GetExtension(hpf.FileName), "") Then
iFailedCnt = iFailedCnt + 1
Exit For
End If
Next
Else
' SAVE THE FILE IN A FOLDER.
hpf.SaveAs(Server.MapPath("\\Destinationpath\testing") & _
Path.GetFileName(hpf.FileName))
iUploadedCnt = iUploadedCnt + 1
End If
End If
End If
Next i
lblUploadStatus.Text = "<b>" & iUploadedCnt & "</b> file(s) Uploaded."
lblFailedStatus.Text = "<b>" & iFailedCnt & _
"</b> duplicate file(s) could not be uploaded."
Else
lblUploadStatus.Text = "Max. 10 files allowed."
End If
Else
lblUploadStatus.Text = "No files selected."
End If
End Sub
Following is the error when I execute this code
Could not find a part of the path 'E:\Destinationpath\testing'.

FSO file rename code running twice

Scenario - OutFolder contains XML files which are named by their created datetime (like 20140524110115, 20140524110120, 20140524110122 and so on). I want to rename these files based on their ID and Action tag values (and check for duplications too).
Problem - When I run the following code, the loop is running twice as many times as number of files in the folder. Currently, the folder contains 67 files and the loop is running 134 times. Hence the files are renamed as
ID11_New_2.xml
ID11_Used_2.xml
ID12_New_2.xml
ID12_Sold_2.xml
... and so on
I was expecting
ID11_New_1.xml
ID11_Used_1.xml
ID12_New_1.xml
ID12_Sold_1.xml
... and so on
Why the loop is running twice?
Sub Test(OutFolder)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.SetProperty "SelectionLanguage", "XPath"
xmlDoc.Async = False
Set objFiles = objFSO.GetFolder(OutFolder).Files
i = 1
For Each FileXML In objFiles
Debug.Print i
xmlDoc.Load (FileXML.Path)
Set varID = xmlDoc.GetElementsByTagName("Id")
Set varAction = xmlDoc.GetElementsByTagName("Action")
If varID.Length > 0 And varAction.Length > 0 Then 'if file is of correct format
FileCtr = 1
varFileName = varID(0).Text & "_" & varAction(0).Text & "_" & FileCtr & ".xml"
'check for duplicates
While objFSO.FileExists(objFSO.BuildPath(OutFolder, varFileName))
varFileName = varID(0).Text & "_" & varAction(0).Text & "_" & FileCtr & ".xml"
FileCtr = FileCtr + 1
Wend
'FileXML.Name = varFileName
With objFSO
.MoveFile .BuildPath(FileXML.ParentFolder, FileXML.Name), .BuildPath(FileXML.ParentFolder, varFileName)
End With
End If
i = i + 1
Next
End Sub
While objFSO.FileExists(objFSO.BuildPath(OutFolder, varFileName))
FileCtr = FileCtr + 1
varFileName = varID(0).Text & "_" & varAction(0).Text & "_" & FileCtr & ".xml"
Wend
And not really sure if the folder where you test for duplicates is the correct one (i don't know what the folders contain), but maybe in ther first line you need to change OutFolder with FileXML.ParentFolder

VBA to find multiple files

I have this code which finds file names(along with file paths) based on search string.This code works fine in finding single files. I would like this macro to find multiple files and get their names displayed separated using a comma.
Function FindFiles(path As String, SearchStr As String)
Dim FileName As String ' Walking filename variable.
Dim DirName As String ' SubDirectory Name.
Dim dirNames() As String ' Buffer for directory name entries.
Dim nDir As Integer ' Number of directories in this path.
Dim i As Integer ' For-loop counter.
Dim Name As String
Dim Annex As String
On Error GoTo sysFileERR
If Right(path, 1) <> "\" Then path = path & "\"
' Search for subdirectories.
nDir = 0
ReDim dirNames(nDir)
DirName = Dir(path, vbDirectory Or vbHidden Or vbArchive Or vbReadOnly _
Or vbSystem) ' Even if hidden, and so on.
Do While Len(DirName) > 0
' Ignore the current and encompassing directories.
If (DirName <> ".") And (DirName <> "..") Then
' Check for directory with bitwise comparison.
If GetAttr(path & DirName) And vbDirectory Then
dirNames(nDir) = DirName
DirCount = DirCount + 1
nDir = nDir + 1
ReDim Preserve dirNames(nDir)
'List2.AddItem path & DirName ' Uncomment to list
End If ' directories.
sysFileERRCont:
End If
DirName = Dir() ' Get next subdirectory.
Loop
' Search through this directory and sum file sizes.
FileName = Dir(path & SearchStr, vbNormal Or vbHidden Or vbSystem _
Or vbReadOnly Or vbArchive)
'Sheet1.Range("C1").Value2 = path & "\" & FileName
While Len(FileName) <> 0
FindFiles = path & "\" & FileName
FileCount = FileCount + 1
' Load List box
' Sheet1.Range("A1").Value2 = path & FileName & vbTab & _
FileDateTime(path & FileName) ' Include Modified Date
FileName = Dir() ' Get next file.
Wend
' If there are sub-directories..
If nDir > 0 Then
' Recursively walk into them
For i = 0 To nDir - 1
FindFiles = path & "\" & FileName
Next i
End If
AbortFunction:
Exit Function
sysFileERR:
If Right(DirName, 4) = ".sys" Then
Resume sysFileERRCont ' Known issue with pagefile.sys
Else
MsgBox "Error: " & Err.Number & " - " & Err.Description, , _
"Unexpected Error"
Resume AbortFunction
End If
End Function
Sub Find_Files()
Dim SearchPath As String, FindStr As String, SearchPath1 As String
Dim FileSize As Long
Dim NumFiles As Integer, NumDirs As Integer
Dim Filenames As String, Filenames1 As String
Dim r As Range
'Screen.MousePointer = vbHourglass
'List2.Clear
For Each cell In Range("SS")
SearchPath = Sheet3.Range("B2").Value2
SearchPath1 = Sheet3.Range("B3").Value2
FindStr = Cells(cell.Row, "H").Value
Filenames = FindFiles(SearchPath, FindStr)
Filenames1 = FindFiles(SearchPath1, FindStr)
'Sheet1.Range("B1").Value2 = NumFiles & " Files found in " & NumDirs + 1 & _
" Directories"
Cells(cell.Row, "F").Value = Filenames
Cells(cell.Row, "G").Value = Filenames1
'Format(FileSize, "#,###,###,##0") & " Bytes"
'Screen.MousePointer = vbDefault
Next cell
End Sub
Any thoughts will be highly appreciated.
I realize this question is very old, but it is unanswered. Here is a quick method for finding multiple files and their paths. VBA's DIR function isn't really very handy, but CMD's DIR function is well optimized and has a plethora of command line switches to make it return only files (or even just folders) that match your criteria. The trick is to call DIRfrom a WScript shell so that the output can be parsed by VBA.
For example, this snippet of code will find every file on your system that starts with config.
Dim oShell As Object 'New WshShell if you want early binding
Dim cmd As Object 'WshExec if you want early binding
Dim x As Integer
Const WshRunning = 0
Set oShell = CreateObject("Wscript.Shell")
Set cmd = oShell.Exec("cmd /c ""Dir c:\config* /a:-d /b /d /s""")
Do While cmd.Status = WshRunning
DoEvents
Loop
Debug.Print cmd.StdOut.ReadAll
Set oShell = Nothing
Set cmd = Nothing