Read data from file with certain extension - file-io

I am working with a VB script to read data from a text file. It works fine.
My challenge is that the file name changes everyday with date appended to it. The file is a text file and end with .TXT extension. Thus every time I have to rename the file to a fixed name that I have used in my script.
Is there a way to read a file from the current folder and with extension .TXT irespective of the name of the file. In the following code I am reading SNMP.TXT file, but the filename could be SNMP_20130415_xxxx.TXT one day and the SNMP_10130416_xxxx.TXT next day and so on.
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objInpoutFile = objFSO.OpenTextFile("D:\scripts\vb\FileHandleScript\SNMP.TXT",1)
Set objOutputFile = objFSO.OpenTextFile("D:\scripts\vb\FileHandleScript\snmp.csv",2,True)

An alternative without regular expression:
For Each f in objFSO.GetFolder("D:\scripts\vb\FileHandleScript").Files
name = LCase(f.Name)
If Left(name, 5) = "snmp_" And objFSO.GetExtensionName(name) = "txt" Then
'do stuff
End If
Next

Loop over the files in the folder, use a RegExp to find the file to process, exit the loop after having processed the file:
Dim reFiNa : Set reFiNa = New RegExp
reFiNa.IgnoreCase = True
reFiNa.Pattern = "^snmp_.+\.txt$" ' starting with snmp_, ending with .txt
For Each oFile in objFSO.GetFolder("D:\scripts\vb\FileHandleScript").Files
If reFiNa.Test(oFile.Name) Then
... process file ...
Exit For
End If
Next

Related

Word VBA error 4199 File not found for existing file, called from OneDrive document

I have a macro to copy some styles from a reference dotx file in the Template folder into the file I am editing. It works well if the file is purely in my local drive, but I receive a File not found error, code 4199, if the file being edited sits (locally) in OneDrive (business). Here is the code; the not-found file is in variable tpl, which points to an existing and valid file. If I run the same macro on the same file, but this time the file sits purely in a local folder, then there is no error.
I looked for similar cases online, but this seems to be an obscure occurrence. Thanks for any help!
'--start
Sub GetStylesfromTemplate_zToCStyleforReports()
Dim i, max As Integer
Dim Hdgs(11 + 1) As String
Dim tpl As String 'Complete path to template file
'Number of styles
max = 2
'List of styles
Hdgs(1) = "TOC 1": Hdgs(2) = "TOC 2"
' Environmental var plus end of template path and file name
tpl = Environ("APPDATA") & "\Microsoft\Templates\Report-ToC-Style-Here.dotx"
For i = 1 To max
Application.OrganizerCopy _
source:=tpl, _
Destination:=ActiveDocument, Name:=Hdgs(i), Object:=wdOrganizerObjectStyles
Next
End Sub
' -- End

VB.NET file error 75 - Path/File Access Error - how is my file locked? I need to delete it

i'm getting a error 75 - file/path access error when i attempt to delete my file (last lines of the code block below):
' make a reference to a directory
Dim directory As New IO.DirectoryInfo(WatchDirectory) 'ex C:\Print\Realtime\
Dim directoryList As IO.FileInfo() = directory.GetFiles(WatchFilter) 'ex *.xml
Dim directoryFile As IO.FileInfo
'list the names of all files in the specified directory
For Each directoryFile In directoryList
'scans the Realtime folder (WatchDirectory) for each specified file (WatchFilter / xml) for processing.
If directoryFile.Name = RealTimeFile Then
'checks if the file is realtime by matching the name up to the ProcessRealtimeFile app setting (ex realtime.xml)
Continue For
Else
'this is not a ProcessRealtimeFile app setting (ex realtime.xml) file
Dim Name As String
Dim renameRetries As Integer = 5
'get file name without extension
Name = IO.Path.GetFileNameWithoutExtension(directoryFile.Name)
While True
Try
If File.Exists(ProcessDirectory & RealTimeFile) = False Then
'the current file to be checked against in the watch directory does not exist in the processdirectory (ex. C:\Print\Oracle\xml.rt\). continue.
Log.Write(Log.Level.Information, "RTPrint-Diamond", Environment.UserName, Environment.MachineName, "File " & directoryFile.FullName & " is being processed by scrape.")
If ArchiveXML = True Then
'copy the current file to the archive directory (ex C:\print\xml.rt\archive\), overwriting the existing file if exists
System.IO.File.Copy(directoryFile.FullName, ArchiveDirectory & directoryFile.Name, True)
End If
'update the date and time of the active file to now
System.IO.File.SetLastWriteTime(directoryFile.FullName, Date.Now)
Log.Write(Log.Level.Information, "RTPrint-Diamond", Environment.UserName, Environment.MachineName, "Date Changed.")
If ISPublisher(directoryFile.FullName) Then
'Current file is a publisher file. Process
Dim fileInfo As New IO.FileInfo(directoryFile.FullName)
Dim utf8WithoutBOM As New System.Text.UTF8Encoding(False) 'file encoding type - UTF8 w/o BOM
Using writer As StreamWriter = New StreamWriter(Path.Combine(PublisherProcessDirectory, directoryFile.Name), False, utf8WithoutBOM)
'set up write to the publisher process directory (ex C:\print5x\xml.rt\)
'publisher requires utf8 w/o BOM to read the file. We need to change the encoding type to this standard.
'this converts the file to utf8 w/o BOM to the 5x output destination
Using reader As StreamReader = fileInfo.OpenText
While Not reader.EndOfStream
Dim line As String = reader.ReadLine
writer.Write(line & vbCrLf)
End While
reader.Close()
End Using
writer.Close()
End Using
If File.Exists(Path.Combine(PublisherProcessDirectory, directoryFile.Name)) Then
'make sure the destination file was successfully re-written in utf8 w/o bom and delete the source file
If IsFileOpen(directoryFile.FullName, 1) = True Then
Microsoft.VisualBasic.FileClose(1)
End If
System.IO.File.Delete(directoryFile.FullName)
End If
I even tested with some sample solutions I read on this site to run a function test to see if the lock is present (giving error 75), and if true is returned, attempt a file close which also is not doing anything.
Obviously my writer.Close() is not doing the job. Can anyone spot why the System.IO.File.Delete(directoryFile.FullName) is not allowing me access to this text file for deletion, and how i can unlock it to delete? Is it the for each that is locking my file? I need to delete the file within the loop, so if the for loop is locking me, what are the work-arounds here?
Additionally, i tested the delete by removing the entire writer block and 2 declared variables above it, and the file still had a lock. This can help to isolate the issue to the surrounding logic and not the streamWriter portion.
Thanks in advance!

VBA file = Dir() retrieving a gibberish filename

Block of code handling looping through files in a directory:
Dim file As Variant
file = Dir(directory)
While (file <> "")
If (InStr(file, ".xlsx") > 0) And (InStr(file, "Percentage") = 0) And (InStr(file, aggregateFilename) = 0) Then
Call fight_dynamics_by_percentage_buckets(aggregateFilename, directory, file, folderToRunMacro, num_buckets)
End If
file = Dir
Wend
Earlier in my code, the user selects a directory storing a set of files. In my test directory, I have the following files:
Analyzed.11.14.383.Chamber1.xlsx
Analyzed.11.14.383.Chamber2.xlsx
Analyzed.11.14.383.Chamber3.xlsx
When I run the macro, the program extracts the filenames as:
Analyzed.11.14.383#494E5A0.xlsx
Analyzed.11.14.383#494E5A1.xlsx
Analyzed.11.14.383#494E5A2.xlsx
I have used this exact code before on previous directories, and have had no trouble extracting the correct filenames.
What's going on here?
I do not see any issue with your code and it is working fine for me as well. It may be a specific system of excel issue. You can use another option to get the same result and here are the codes for your reference. Have a good day
Set filesys = CreateObject("Scripting.FileSystemObject")
For Each sfile In filesys.GetFolder(directory).Files
file = filesys.GetFileName(sfile)
If (InStr(file, ".xlsx") > 0) And (InStr(file, "Percentage") = 0) And (InStr(file, aggregateFilename) = 0) Then
Call fight_dynamics_by_percentage_buckets(aggregateFilename, directory, file, folderToRunMacro, num_buckets)
End If
Next

Count Specific lines in a text file (that start with a number)

As a part of an application that i am building in VB.net, i am trying to import multiple txt files and be able to count how many lines of that file start with a specific number (for example 1) and show it in a message box.
Here is my code so far:
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
For Each File In OpenFileDialog1.FileNames
My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
For Each fileName In OpenFileDialog1.FileNames
For Each line As String In System.IO.File.ReadLines(fileName)
Dim Linecount = line.count
If line.StartsWith("1") Then
MsgBox(LineCount)
End If
Next
Next
Next
The above code does not work as it gives me wrong number of lines. In my txt file i have only one line that starts with "1".
You are just showing the number of characters in each line here:
For Each line As String In System.IO.File.ReadLines(fileName)
Dim Linecount = line.Count ' Number of characters
You could use LINQ to get the number of lines that start with one:
Dim lineWithOne = File.ReadLines(fileName).Count(Function(l) l.StartsWith("1"))
If you don't want or can't use LINQ, this is the classic way:
Dim lineWithOne = 0
For Each line As String In System.IO.File.ReadLines(fileName)
If line.StartsWith("1") Then lineWithOne += 1
Next

Rename a file extension in VB.NET

I've written a data sorter which writes out a .build extension to the files it's writing to so nothing tries to lift it as it's writing data to particular files.
At the end, I want to rename anything with a .build extension to a .dat before the program closes.
For Each f In outputFiles
For Each r In TrailerRecords
' Set the bill count variable
If r.VariableField Then
r.Fields(1) = String.Format("{0:000000}", f.Value)
End If
' Write the trailer record to the output file
File.AppendAllText(f.Key, r.ToString() & vbLf)
Next
' Rename all.build files to .dat
NEEDS TO GO HERE
' Copy each output file to the backup directory
File.Copy(f.Key, Path.Combine(backupFolder, Path.GetFileName(f.Key)), True)
Next
End Sub
Get the files and rename it:
Dim auxFile as String
Dim files() As String = IO.Directory.GetFiles(myFolderPath, "*.build")
For Each sFile As String In files
auxFile = IO.Path.GetFileNameWithoutExtension(sFile) & ".dat"
My.Computer.FileSystem.RenameFile(sFile, auxFile)
Next
You can use File.Copy() with the overwrite property to True instead.
Take a look at the MSDN documentation:
GetFiles
RenameFile
Copy
GetFilenameWithoutExtension