vb.net how to loop through a directory listing? - vb.net

How can I loop through a folder getting each file listed and when its date/time?

Use DirectoryInfo.GetFiles() and extract the data (Name, CreationTime, etc.) from the FileInfo class.
I've pasted some code from the MSDN page here.
Imports System
Imports System.IO
Public Class GetFilesTest
Public Shared Sub Main()
' Make a reference to a directory.
Dim di As New DirectoryInfo("c:\")
' Get a reference to each file in that directory.
Dim fiArr As FileInfo() = di.GetFiles()
' Display the names of the files.
Dim fri As FileInfo
For Each fri In fiArr
Console.WriteLine(fri.Name)
Next fri
End Sub 'Main
End Class 'GetFilesTest

For Each LogFile In Directory.GetFiles(Application.StartupPath & "\Txt\")
' do whatever wtih filename
Next

we have the chance to develop in VB.Net (not in Java) and some variable's definitions can be shortened.
I still use GetFiles() and I have added the code to display the DateTime infos.
Imports System
Imports System.IO
...
Dim dir As New DirectoryInfo(sFolderName)
For Each f In dir.GetFiles()
Console.WriteLine(">> FILE-NAME: [" & f.Name & "]")
Console.WriteLine(">> UPDATE-DATE: " & f.lastWriteTime.toString("yyyy-MM-dd"))
Console.WriteLine(">> CREATE-DATE: " & f.creationTime.toString("yyyy-MM-dd"))
Next

Related

How can i open .exe file from the multiple folders in single click using vb.net or any other way?

How can i open .exe file from the multiple folders in single click using vb.net or any other way?
tried using process.start method but it's not working properly and found error can't find path.
Example:
For Each Dir As String In Directory.GetDirectories(Application.StartupPath)
Process.Start(Dir & "\" & "*.exe")
Next
This will try to run all EXE files in the folder "myPath" and subfolders
Imports System.IO
Module Module1
Sub Main()
Dim pattern As String
pattern = "*.EXE"
Dim myPath As String
myPath = "your Path" ' Adjust to your needs
Dim exeLst As IEnumerable(Of String)
exeLst = Directory.EnumerateFiles(myPath, pattern, SearchOption.AllDirectories)
Dim sngFile As String
For Each sngFile In exeLst
Process.Start(sngFile)
Next
End Sub
End Module

vb.net convert multiple pdf files to excel using Bytescout pdf extractor

i want to convert multiple pdf files into excel using bytescout pdf extractor can anyone help me with this. i am able to extract single pdf file.
however i am getting error while doing for multiple files.
here is the error what i am getting.
Here is my code.
Imports System.Threading
Imports Bytescout.PDFExtractor
Imports System.IO
Module Module1
Sub Main()
Try
Dim extractor As New CSVExtractor()
extractor.RegistrationName = "demo"
extractor.RegistrationKey = "demo"
'Dim filenames1 As String() = Directory.GetFiles(Path, "*.TXT")
For Each f In Directory.GetFiles(My.Computer.FileSystem.CurrentDirectory & "\PDF Files\", "*.PDF", SearchOption.TopDirectoryOnly)
extractor.LoadDocumentFromFile(f)
extractor.SaveCSVToFile(My.Computer.FileSystem.CurrentDirectory & "\CSV Files\"(f))
Console.WriteLine("Data has been extracted to CSV file....!" & Environment.NewLine)
Next
Thread.Sleep(3000)
Catch error_t As Exception
Console.WriteLine(error_t.ToString)
Console.ReadKey(True)
End Try
End Sub
End Module
According to the error message the given path's format is not supported could you please verify is the output path is correct? If the path folder or subfolder do not exist then you should create them first using System.IO.Directory.CreateDirectory
You can avoid the error by below code:
path = My.Computer.FileSystem.CurrentDirectory & "\PDF Files\"
For Each f As String In Directory.GetFiles(path, "*.PDF", SearchOption.TopDirectoryOnly)
csvFileName = Replace(IO.Path.GetFileName(f), ".pdf", ".csv")
extractor.LoadDocumentFromFile(f)
extractor.SaveCSVToFile(My.Computer.FileSystem.CurrentDirectory & "\CSV Files\" & csvFileName)
Console.WriteLine("Data has been extracted to CSV file....!" & Environment.NewLine)
Next
You need a file name to write to and the line below line does that.
csvFileName = Replace(IO.Path.GetFileName(f), ".pdf", ".csv")
Let us know if you need further help.
Thanks,
Prakash

Rename files sequentially

with reference to Renaming all files in a folder
on running the below code, get type def errors:
Type 'DirectoryInfo' is not defined
Type 'FileInfo' is not defined
how to resolve these errors. Please suggest.
Dim sourcePath As String = "E:\testrenamerbackup\vbdotnet"
Dim searchPattern As String = "*.doc"
Dim curDir As New DirectoryInfo(sourcePath)
Dim i As Integer = 0
For Each fi As FileInfo In curDir.GetFiles(searchPattern).OrderBy(Function(num) num.CreationTime)
File.Move(fi.FullName, Path.Combine(fi.Directory.FullName, "docFile_" & i & ".doc"))
i += 1
Next
Add Import System.IO on top of your vb.net class file, for example
Imports System
Imports System.IO
Public Class Test
Public Shared Sub Main()
' your code...
End Sub
End Class
System.IO Namespace contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support including DirectoryInfo, FileInfo. by adding Import System.IO you can use those types and methods in the namespace.

Extracting Filename and Path from a running process

I'm writing a screen capture application for a client. The capture part is fine, but he wants to get the name and path of the file that the capture is of.
Using system.diagnostics.process I am able to get the process that the capture is of, and can get the full path of the EXE, but not the file that is open.
ie. Notepad is open with 'TextFile1.txt' as its document. I can get from the process the MainWindowTitle which would be 'TextFile1.txt - Notepad' but what I need is more like 'c:\users....\TextFile1.txt'
Is there a way of getting more information from the process?
I'm sure there is a way, but I can't figure it out
Any help greatly appreciated.
You can use ManagementObjectSearcher to get the command line arguments for a process, and in this notepad example, you can parse out the file name. Here's a simple console app example that writes out the full path and file name of all open files in notepad..
Imports System
Imports System.ComponentModel
Imports System.Management
Module Module1
Sub Main()
Dim cl() As String
For Each p As Process In Process.GetProcessesByName("notepad")
Try
Using searcher As New ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " & p.Id)
For Each mgmtObj As ManagementObject In searcher.Get()
cl = mgmtObj.Item("CommandLine").ToString().Split("""")
Console.WriteLine(cl(cl.Length - 1))
Next
End Using
Catch ex As Win32Exception
'handle error
End Try
Next
System.Threading.Thread.Sleep(1000000)
End Sub
End Module
I had to add a reference to this specific dll:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Managment.dll
i think it is the simplest way
For Each prog As Process In Process.GetProcesses
If prog.ProcessName = "notepad" Then
ListBox1.Items.Add(prog.ProcessName)
End If
Next
I know this post is old, but since I've searched for this two days ago, I'm sure others would be interested. My code below will get you the file paths from Notepad, Wordpad, Excel, Microsoft Word, PowerPoint, Publisher, Inkscape, and any other text or graphic editor's process, as long as the filename and extension is in the title bar of the opened window.
Instead of searching, it obtains the file's target path from Windows' hidden Recent Items directory, which logs recently opened and saved files as shortcuts. I discovered this hidden directory in Windows 7. You're gonna have to check if Windows 10 or 11 has this:
C:\Users\ "username" \AppData\Roaming\Microsoft\Windows\Recent
I slapped this code together under Framework 4, running as 64bit. The COM dlls that must be referenced in order for the code to work are Microsoft Word 14.0 Object Library, Microsoft Excel 14.0 Object Library, Microsoft PowerPoint 14.0 Object Library, and Microsoft Shell Controls And Automation.
For testing, the code below needs a textbox, a listbox, a button, and 3 labels (Label1, FilenameLabel, Filepath).
Once you have this working, after submitting a process name, you will have to click the filename item in the ListBox to start the function to retrieve it's directory path.
Option Strict On
Option Explicit On
Imports System.Runtime.InteropServices
Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop.Word
Imports Microsoft.Office.Interop.PowerPoint
Imports Shell32
Public Class Form1
'function gets names of all opened Excel workbooks, adding them to the ListBox
Public Shared Function ExcelProcess(ByVal strings As String) As String
Dim Excel As Microsoft.Office.Interop.Excel.Application = CType(Marshal.GetActiveObject("Excel.Application"), Microsoft.Office.Interop.Excel.Application)
For Each Workbook As Microsoft.Office.Interop.Excel.Workbook In Excel.Workbooks
Form1.ListBox1.Items.Add(Workbook.Name.ToString() & " - " & Form1.TextBox1.Text)
Next
Return strings
End Function
'function gets names of all opened Word documents, adding them to the ListBox
Public Shared Function WordProcess(ByVal strings As String) As String
Dim Word As Microsoft.Office.Interop.Word.Application = CType(Marshal.GetActiveObject("Word.Application"), Microsoft.Office.Interop.Word.Application)
For Each Document As Microsoft.Office.Interop.Word.Document In Word.Documents
Form1.ListBox1.Items.Add(Document.Name.ToString() & " - " & Form1.TextBox1.Text)
Next
Return strings
End Function
'function gets names of all opened PowerPoint presentations, adding them to the ListBox
Public Shared Function PowerPointProcess(ByVal strings As String) As String
Dim PowerPoint As Microsoft.Office.Interop.PowerPoint.Application = CType(Marshal.GetActiveObject("PowerPoint.Application"), Microsoft.Office.Interop.PowerPoint.Application)
For Each Presentation As Microsoft.Office.Interop.PowerPoint.Presentation In PowerPoint.Presentations
Form1.ListBox1.Items.Add(Presentation.Name.ToString() & " - " & Form1.TextBox1.Text)
Next
Return strings
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'clears listbox to prepare for new process items
ListBox1.Items.Clear()
'gets process title from TextBox1
Dim ProcessName As String = TextBox1.Text
'prepare string's case format for
ProcessName = ProcessName.ToLower
'corrects Office process names
If ProcessName = "microsoft excel" Then
ProcessName = "excel"
Else
If ProcessName = "word" Or ProcessName = "microsoft word" Then
ProcessName = "winword"
Else
If ProcessName = "powerpoint" Or ProcessName = "microsoft powerpoint" Then
ProcessName = "powerpnt"
Else
End If
End If
End If
'get processes by name (finds only one instance of Excel or Microsoft Word)
Dim proclist() As Process = Process.GetProcessesByName(ProcessName)
'adds window titles of all processes to a ListBox
For Each prs As Process In proclist
If ProcessName = "excel" Then
'calls function to add all Excel process instances' workbook names to the ListBox
ExcelProcess(ProcessName)
Else
If ProcessName = "winword" Then
'calls function to add all Word process instances' document names to the ListBox
WordProcess(ProcessName)
Else
If ProcessName = "powerpnt" Then
'calls function to add all Word process instances' document names to the ListBox
PowerPointProcess(ProcessName)
Else
'adds all Notepad or Wordpad process instances' filenames
ListBox1.Items.Add(prs.MainWindowTitle)
End If
End If
End If
Next
End Sub
Private Sub ListBox1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseClick
Try
'add ListBox item (full window title) to string
Dim ListBoxSelection As String = String.Join(Environment.NewLine, ListBox1.SelectedItems.Cast(Of String).ToArray)
'get full process title after "-" from ListBoxSelection
Dim GetProcessTitle As String = ListBoxSelection.Split("-"c).Last()
'create string to remove from ListBoxSelection
Dim Remove As String = " - " & GetProcessTitle
'Extract filename from ListBoxSelection string, minus process full name
Dim Filename As String = ListBoxSelection.Substring(0, ListBoxSelection.Length - Remove.Length + 1)
'display filename
FilenameLabel.Text = "Filename: " & Filename
'for every file opened and saved via savefiledialogs and openfiledialogs in editing software
'Microsoft Windows always creates and modifies shortcuts of them in Recent Items directory:
'C:\Users\ "Username" \AppData\Roaming\Microsoft\Windows\Recent
'so the below function gets the target path from files's shortcuts Windows created
FilePathLabel.Text = "File Path: " & GetLnkTarget("C:\Users\" & Environment.UserName & "\AppData\Roaming\Microsoft\Windows\Recent\" & Filename & ".lnk")
Catch ex As Exception
'no file path to show if nothing was saved yet
FilePathLabel.Text = "File Path: Not saved yet."
End Try
End Sub
'gets file's shortcut's target path
Public Shared Function GetLnkTarget(ByVal lnkPath As String) As String
Dim shl = New Shell32.Shell()
lnkPath = System.IO.Path.GetFullPath(lnkPath)
Dim dir = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath))
Dim itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath))
Dim lnk = DirectCast(itm.GetLink, Shell32.ShellLinkObject)
Return lnk.Target.Path
End Function
End Class

Trouble writing to App.Config file

Having issues reading/writing to App.config.
The code I have below I took from the MSDN article on (AppSettingsSection Class)
http://msdn.microsoft.com/en-us/library/system.configuration.appsettingssection%28v=vs.100%29.aspx
I am successfully able to read the App.config file and get/use the values and it responds correctly if I change the App.config file to get the new values.
However, in this (from MS page) I add a new entry and change a value on one of my initial entries. It appears to change it, does not error in saving it, but does not write it to the file so the next time I run, I am back to my initial values in App.config.
Can someone show me my erroneous ways?
TIA!
Imports System
Imports System.Collections.Specialized
Imports System.Configuration
Imports System.Text
Imports System.IO
' IMPORTANT: To compile this example, you must add to the project
' a reference to the System.Configuration assembly.
'
Module Module1
Sub Main()
Dim KeypairHolder As String = Nothing
' Get Configuration File as config object
Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
' Create a unique key/value pair to add to the appSettings section.
Dim keyName As String = "DateTimeStamp Number " & config.AppSettings.Settings.Count + 1
Dim value As String = String.Concat(Date.Now.ToLongDateString(), " ", Date.Now.ToLongTimeString())
' Create appSettings as object
Dim appSettings As System.Configuration.AppSettingsSection = config.AppSettings
' add the new key and value
appSettings.Settings.Add(keyName, value)
' save and refresh the values
config.Save(ConfigurationSaveMode.Modified)
' Force a reload in memory of the changed section.
ConfigurationManager.RefreshSection("appSettings")
' Get keys
Dim kAll() As String = appSettings.Settings.AllKeys()
' Build string to display
For Each key In kAll
KeypairHolder = KeypairHolder & key & ": " & appSettings.Settings(key).Value & vbCrLf
Next
'Display
MsgBox(KeypairHolder)
' Change a value
appSettings.Settings("CustomKey").Value = "Changed Value"
' Resave and get and display
config.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")
kAll = appSettings.Settings.AllKeys()
KeypairHolder = Nothing
For Each key In kAll
KeypairHolder = KeypairHolder & key & ": " & appSettings.Settings(key).Value & vbCrLf
Next
MsgBox(KeypairHolder)
End Sub
End Module
' appSettings Section of my App.Config file
' <appSettings>
' <add key="UsernamePassword" value="BobsUsername:BobsPassword"/>
' <add key="CustomKey" value="ConfigApp Value"/>
' </appSettings>
Right click on the app.config file in your solution explorer window and select the Properties option. Ensure that the Copy to Output Directory property is NOT set to Copy always.