Load Image files from folder - vb.net

I have a checked list box and a thumbnail area to display them where I am trying to load only images from a specific folder and need to display in thumbnails area but the problem is there is a thumbs.db file which is also being added to the checked list box which I don't need it.
So how do I actually load only the image files without the thumbs.db file.
Here is my code:
Private Sub LoadProjectToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LoadProjectToolStripMenuItem.Click
Using ofdlg As New Windows.Forms.OpenFileDialog
ofdlg.DefaultExt = "trk"
ofdlg.Filter = "Project|*.trk"
ofdlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If ofdlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim SaveData As New gCanvasData
Using objStreamReader As New StreamReader(ofdlg.FileName)
Dim x As New XmlSerializer(GetType(gCanvasData))
SaveData = CType(x.Deserialize(objStreamReader), gCanvasData)
objStreamReader.Close()
End Using
With SaveData
'gTSSizer_gAZoom.Value = 100
GCanvas1.ImageXYReset()
GCanvas1.Image = .Image
GCanvas1.gAnnotates = .gAnnotates
GCanvas1.RebuildAll()
GCanvas1.AssembleBitmap()
End With
Dim fullpath As String
fullpath = Application.StartupPath + "\" & System.IO.Path.GetFileNameWithoutExtension(ofdlg.FileName) + "\"
For Each fi As FileInfo In New DirectoryInfo(fullpath).GetFiles
CheckedListBox1.Items.Add(Application.StartupPath + "\" & System.IO.Path.GetFullPath(ofdlg.FileName))
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i, True)
ThumbControl1.AddFolder(fullpath, True)
Next i
Next
End If
End Using
End Sub

Either filter it inside of the For Each Loop:
For Each fi As FileInfo In New DirectoryInfo(fullpath).GetFiles
If Not {".jpg", ".png", ".bmp"}.Contains(fi.Extension) Then Continue For
' ...
Next
or do it in the GetFiles:
DirectoryInfo(fullpath).GetFiles(".jpg")

Found the solution at last:
Dim fullpath As String
fullpath = Application.StartupPath & "\" & System.IO.Path.GetFileNameWithoutExtension(ofdlg.FileName) + "\"
Dim FileDirectory As New IO.DirectoryInfo(fullpath)
Dim FileJpg As IO.FileInfo() = FileDirectory.GetFiles("*.jpg")
Dim FileGif As IO.FileInfo() = FileDirectory.GetFiles("*.gif")
Dim FileBmp As IO.FileInfo() = FileDirectory.GetFiles("*.bmp")
For Each File As IO.FileInfo In FileJpg
CheckedListBox1.Items.Add(File.FullName)
Dim str As String
str = Directory.GetCurrentDirectory() & "\" & "Backup\"
Next
For Each File As IO.FileInfo In FileGif
CheckedListBox1.Items.Add(File.FullName)
Dim str As String
str = Directory.GetCurrentDirectory() & "\" & "Backup\"
Next
For Each File As IO.FileInfo In FileBmp
CheckedListBox1.Items.Add(File.FullName)
Dim str As String
str = Directory.GetCurrentDirectory() & "\" & "Backup\"
Next
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i, True)
Next i

Change DirectoryInfo(fullpath).GetFiles to DirectoryInfo(fullpath).EnumerateFiles() And add a search pattern for the image file extensions you want. http://msdn.microsoft.com/en-us/library/dd383574.aspx

Related

Making a program that zip files but having error The process cannot access the file because it is being used by another process

I am trying to make a program that will zip all the files in the same folder.
But I'm having issues with it. It's giving me an error saying the file is being used by another process.
Private Sub btnZip_Click(sender As Object, e As EventArgs) Handles btnZip.Click
Dim extension As String = txtExtension.Text
Dim paths As String = Application.StartupPath
Dim files As String() = Directory.GetFiles(paths, "*.*")
For Each file As String In files
Dim fileName As String = path.GetFileNameWithoutExtension(file)
Dim index As Integer = fileName.IndexOf("_")
If index >= 0 Then
fileName = fileName.Substring(0, index)
End If
ZipFile.CreateFromDirectory(Path.GetDirectoryName(file), paths & "\" & fileName & ".zip", CompressionLevel.Optimal, False)
Next
MessageBox.Show("Files zipped successfully!")
End Sub
I just couldn't figure out what's causing the issue.
as seen in comment, you must exclude your running application from the file list :
add
If Path.GetFileName(file) = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) Then Continue For
in for loop
Private Sub btnZip_Click(sender As Object, e As EventArgs) Handles btnZip.Click
Dim extension As String = txtExtension.Text
Dim paths As String = Application.StartupPath
Dim files As String() = Directory.GetFiles(paths, "*.*")
For Each file As String In files
If Path.GetFileName(file) = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) Then Continue For
Dim fileName As String = Path.GetFileNameWithoutExtension(file)
Dim index As Integer = fileName.IndexOf("_")
If index >= 0 Then
fileName = fileName.Substring(0, index)
End If
ZipFile.CreateFromDirectory(Path.GetDirectoryName(file), paths & "\" & fileName & ".zip", CompressionLevel.Optimal, False)
Next
MessageBox.Show("Files zipped successfully!")
End Sub

I Want to add a Timestamp with the original Name of the Folders name that is being Copied (in vb.net)

I found some Code to Copy a Folder with all its contents to another folder. the Folder name that is being copied to another folder is the same as the original folder in its original path. I want to add a timestamp with a date and time to show you the most recent 'copy' of the folder you copied.
An example would be:
Original Folder: Rage 2 ;
Copied Folder: Rage 2 - 3/11/2021 - 7:37
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim parts As String() = directoryTargetLocation.Split(New Char() {"\"c})
Dim filename As String = parts(parts.Count - 1) 'target folder name
Dim dir_path As String = "" 'directory without target folder name
For f As Integer = 0 To parts.Count - 2
dir_path += parts(f) + "\"
Next
Dim copied As Integer = 0
Dim counter As Integer = IO.Directory.GetFiles(directoryTargetLocation, "*.*", IO.SearchOption.AllDirectories).Length 'counts the number of files
SetProgressbar(counter, ProgressBar2) 'Sets ProgressBar maximum to number of files
setLabelTxt("Copied (0/" + counter.ToString + ")", Label4) 'displays the amount of copied files
Dim FolderList As New List(Of String)
FolderList.Add(directoryTargetLocation) 'Set first folder
Do While True
If (BackgroundWorker1.CancellationPending = True) Then 'cancel loop
e.Cancel = True
Exit Do
End If
Dim FoldersInsideDirectory As New List(Of String)
If FolderList.Count = 0 Then
Exit Do 'If there is no folder to copy Exit Do
Else
For l As Integer = 0 To FolderList.Count - 1
If (BackgroundWorker1.CancellationPending = True) Then 'stop for loop
e.Cancel = True
Exit For
End If
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(FolderList(l))
Dim dest As String = FolderList(l).Replace(dir_path, "")
If (Not System.IO.Directory.Exists(Destinydirectory + "\" + dest)) Then 'create subFolder inside directory
System.IO.Directory.CreateDirectory(Destinydirectory + "\" + dest)
End If
Dim fileSystemInfo As System.IO.FileSystemInfo
For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
If (BackgroundWorker1.CancellationPending = True) Then
e.Cancel = True
Exit For
End If
Dim destinationFileName As String = System.IO.Path.Combine(Destinydirectory + "\" + dest, fileSystemInfo.Name)
If TypeOf fileSystemInfo Is System.IO.FileInfo Then
Dim streamRead As New System.IO.FileStream(fileSystemInfo.FullName, System.IO.FileMode.Open)
setLabelTxt(fileSystemInfo.FullName.ToString, LabelProgress)
Dim streamWrite As New System.IO.FileStream(Destinydirectory + "\" + dest + "\" + fileSystemInfo.Name, IO.FileMode.Create, IO.FileAccess.Write, IO.FileShare.None)
Dim lngLen As Long = streamRead.Length - 1
setLabelTxt("Copy bytes : (0/" + (lngLen * 100).ToString + ")", Label10)
Dim byteBuffer(1048576) As Byte 'our stream buffer
Dim intBytesRead As Integer 'number of bytes read
While streamRead.Position < lngLen 'keep streaming until EOF
If (BackgroundWorker1.CancellationPending = True) Then
e.Cancel = True
Exit While
End If
BackgroundWorker1.ReportProgress(CInt(streamRead.Position / lngLen * 100))
setLabelTxt("Copy bytes : (" + CInt(streamRead.Position).ToString + "/" + (lngLen * 100).ToString + ")", Label10)
intBytesRead = (streamRead.Read(byteBuffer, 0, 1048576))
streamWrite.Write(byteBuffer, 0, intBytesRead)
End While
'Clean up
streamWrite.Flush()
streamWrite.Close()
streamRead.Close()
addProgress(1, ProgressBar2)
copied += 1
setLabelTxt("Copied (" + copied.ToString + "/" + counter.ToString + ")", Label4)
Else
FoldersInsideDirectory.Add(fileSystemInfo.FullName)
End If
Next
Next
FolderList.Clear()
FolderList = FoldersInsideDirectory
End If
Loop
End Sub
Before:
Dim streamWrite As New System.IO.FileStream(Destinydirectory + "\" + dest + "\" + fileSystemInfo.Name, IO.FileMode.Create, IO.FileAccess.Write, IO.FileShare.None)
After:
dim fnbase as string = Path.GetFileNameWithoutExtension(fileSystemInfo.Name)
dim fnexten as string = path.getextension(fileSystemInfo.Name)
dim fndate as string = DateTime.Now.ToString("yyyyMMdd HHmmss")
dim fn as string = $"{fnbase} - {fndate}{fnexten}"
Dim streamWrite As New System.IO.FileStream(Destinydirectory + "\" + dest + "\" + fn, IO.FileMode.Create, IO.FileAccess.Write, IO.FileShare.None)
I broke this down the way I did just so it was really easy for you to see the different pieces of it. You could just as easily put all of this together dynamically as the value you pass to System.IO.FileStream.
As an aside, you're doing the copy itself the complicated way. Maybe you need to use that method for a specific reason, but if not, maybe consider File.Copy next time.

Drag and drop multiple files by filter into listview

I'm currently have this code to store data to listview
I have to store first the info to textbox lines and then store them to listview.
Is there easy way without storing first textbox and directly put the files into listview?
What I want is to drag and drop or browse the multiple video ts file in the first column and then the srt in the sub column.
hope that you know what I mean. I'm rally new in listview
Sub AddToListView()
LV.Items.Clear()
Dim vn = vName.Lines
Dim sn = sName.Lines
Dim vp = vPath.Lines
Dim sp = sPath.Lines
Dim items As New List(Of ListViewItem)
Dim upper = {vn.GetUpperBound(0), sn.GetUpperBound(0), vp.GetUpperBound(0), sp.GetUpperBound(0)}
For I = 0 To upper.Min
items.Add(New ListViewItem({vn(I), sn(I), vp(I), sp(I)}))
Next
LV.BeginUpdate()
LV.Items.AddRange(items.ToArray())
SortItems()
LV.EndUpdate()
AddToParam()
End Sub
Sub readFiles()
Dim folder As String = txtinputFolder.Text
Dim sb1 As New StringBuilder
Dim sb2 As New StringBuilder
Dim sb3 As New StringBuilder
Dim sb4 As New StringBuilder
For Each item In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
sb1.Append(item & vbNewLine)
Next
vPath.Text = ""
vPath.Text = sb1.ToString.Trim
For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
sb2.Append(Path.GetFileName(file) & vbNewLine)
Next
vName.Text = ""
vName.Text = sb2.ToString.Trim
For Each file As String In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
sb3.Append(Path.GetFileName(file) & vbNewLine)
Next
sName.Text = ""
sName.Text = sb3.ToString.Trim
For Each item3 In My.Computer.FileSystem.GetFiles(folder, FileIO.SearchOption.SearchTopLevelOnly, "*.srt")
sb4.Append(item3 & vbNewLine)
Next
sPath.Text = ""
sPath.Text = sb4.ToString.Trim
End Sub
If i'm not wrong subtitle name should be the same as the movie
Sub readFiles(ByVal searchdirectory As String)
For Each FullPath In My.Computer.FileSystem.GetFiles(searchdirectory, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
Dim parentPath As String = Path.GetDirectoryName(FullPath)
Dim movieName As String = Path.GetFileNameWithoutExtension(FullPath)
Dim srtPath As String = parentPath & "\" & movieName & ".srt"
If File.Exists(srtPath) Then
Lv.Items.Add(FullPath).SubItems.AddRange(New String() {movieName & ".ts", srtPath, movieName & ".srt"})
Else
Lv.Items.Add(FullPath).SubItems.AddRange(New String() {movieName & ".ts", "Not Exist", "No subtitle"})
End If
Next
Lv.Sorting = SortOrder.Ascending
Lv.Sort()
End Sub
usage
readFiles("you path")
You could try something like this:
Sub AddToListView(vNames As String(), sNames As String(), vPaths As String(), sPaths As String())
LV.Items.Clear()
Dim items As New List(Of ListViewItem)
Dim upperBounds = {vNames.GetUpperBound(0), sNames.GetUpperBound(0), vPaths.GetUpperBound(0), sPaths.GetUpperBound(0)}
For i = 0 To upperBounds.Min
items.Add(New ListViewItem({vNames(i), sNames(i), vPaths(i), sPaths(i)}))
Next
LV.BeginUpdate()
LV.Items.AddRange(items.ToArray())
SortItems()
LV.EndUpdate()
AddToParam()
End Sub
Sub readFiles()
Dim folder As String = txtinputFolder.Text
Dim vPaths As New List(Of String)
Dim vNames As New List(Of String)
Dim sPaths As New List(Of String)
Dim sNames As New List(Of String)
For Each filePath In Directory.EnumerateFiles(folder, "*.ts")
vPaths.Add(filePath)
vNames.Add(Path.GetFileName(filePath))
Next
For Each filePath In Directory.EnumerateFiles(folder, "*.srt")
sPaths.Add(filePath)
sNames.Add(Path.GetFileName(filePath))
Next
AddToListView(vNames.ToArray(), sNames.ToArray(), vPaths.ToArray(), sPaths.ToArray())
End Sub
If you don't want readFiles calling AddToListView, you could use fields to store the data rather than local variables, or you could have readFields return the data in a Tuple or some dedicated object.
This seems like a reasonable answer based on the code provided and the actual question asked but it has nothing to do with drag and drop, so I'm not sure whether I'm missing something or you are.
Thank you here's my updated code:
since I want to show first the filename I tried to re-edit the code.
Sub readFiles(ByVal searchdirectory As String)
For Each FullPath In My.Computer.FileSystem.GetFiles(searchdirectory, FileIO.SearchOption.SearchTopLevelOnly, "*.ts")
Dim parentPath As String = Path.GetDirectoryName(FullPath)
Dim movieName As String = Path.GetFileNameWithoutExtension(FullPath)
Dim srtPath As String = parentPath & "\" & movieName & ".srt"
Dim allPath As String = parentPath & "\" & movieName
If File.Exists(srtPath) Then
LV.BeginUpdate()
Dim lvi As New ListViewItem
With lvi
.Text = movieName & ".ts" 'video filename
.SubItems.Add(movieName & ".srt") 'subtitle filename
.SubItems.Add(movieName & ".mkv") 'output filename
.SubItems.Add(allPath & ".ts") 'video path
.SubItems.Add(allPath & ".srt") 'subtitle path
End With
LV.Items.Add(lvi)
LV.EndUpdate()
Else
MsgBox("srt file not found in the folder", vbInformation, "")
End If
Next
LV.Sorting = SortOrder.Ascending
LV.Sort()
End Sub

VB.net Check items in a text doc and see if it's in a folder

I have a text document with a list of file names and their extensions. I need to go through this list and check a directory for the existence of each file. I then need to output the result to either foundFilesList.txt or OrphanedFiles.txt. I have two approaches to this function, and neither is working. The first example uses a loop to cycle through the text doc. The second one doesn't work it never sees a match for the file from the fileNamesList.
Thank you for taking the time to look at this.
First Code:
Dim FILE_NAME As String
FILE_NAME = txtFileName.Text
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
fCount = 0
For i = 0 To fileNames.Count() - 1
Dim fileName = fileNames(i)
'sFileToFind = location & "\" & fileName & "*.*"
Dim paths = IO.Directory.GetFiles(location, fileName, IO.SearchOption.AllDirectories)
If Not paths.Any() Then
System.IO.File.AppendAllText(orphanedFiles, fileName & vbNewLine)
Else
For Each pathAndFileName As String In paths
If System.IO.File.Exists(pathAndFileName) = True Then
Dim sRegLast = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toFileLoc = System.IO.Path.Combine(createXMLFldr, sRegLast)
Dim moveToFolder = System.IO.Path.Combine(MoveLocation, "XML files", sRegLast)
'if toFileLoc = XML file exists move it into the XML files folder
If System.IO.File.Exists(toFileLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveToFolder, True)
System.IO.File.AppendAllText(ListofFiles, sRegLast & vbNewLine)
fileFilename = (fileName) + vbCrLf
fCount = fCount + 1
BackgroundWorker1.ReportProgress(fCount)
'fileCount.Text = fCount
End If
End If
Next
End If
BackgroundWorker1.ReportProgress(100 * i / fileNames.Count())
'statusText = i & " of " & fileName.Count() & " copied"
fCount = i
Next
Second Code:
FILE_NAME = txtFileName.Text 'textfield with lines of filenames are located ]
Dim fileNamesList = System.IO.File.ReadAllLines(FILE_NAME)
location = txtFolderPath.Text
fCount = 0
' Two list to collect missing and found files
Dim foundFiles As List(Of String) = New List(Of String)()
Dim notfoundFiles As List(Of String) = New List(Of String)()
Dim fileNames As String() = System.IO.Directory.GetFiles(createXMLFldr)
For Each file As String In fileNamesList
Debug.Write("single file : " & file & vbCr)
' Check if the files is contained or not in the request list
Dim paths = IO.Directory.GetFiles(location, file, IO.SearchOption.AllDirectories)
If fileNamesList.Contains(Path.GetFileNameWithoutExtension(file)) Then
Dim FileNameOnly = Path.GetFileName(file)
Debug.Write("FileNameOnly " & FileNameOnly & vbCr)
If System.IO.File.Exists(FileNameOnly) = True Then
'if toFileLoc = XML file exists move it into the XML files folder
Dim moveToFolder = System.IO.Path.Combine(MoveLocation, "XML files", file)
foundFiles.Add(file) 'add to foundFiles list
fileFilename = (file) + vbCrLf 'add file name to listbox
fCount = fCount + 1
Else
notfoundFiles.Add(file)
End If
End If
Next
File.WriteAllLines(ListofFiles, foundFiles)
File.WriteAllLines(orphanedFiles, notfoundFiles)
This is just a starting point for you, but give it a try:
Friend Module Main
Public Sub Main()
Dim oFiles As List(Of String)
Dim _
sOrphanedFiles,
sSearchFolder,
sFoundFiles,
sTargetFile As String
sOrphanedFiles = "D:\Results\OrphanedFiles.txt"
sSearchFolder = "D:\Files"
sFoundFiles = "D:\Results\FoundFiles.txt"
oFiles = IO.File.ReadAllLines("D:\List.txt").ToList
oFiles.ForEach(Sub(File)
If IO.Directory.GetFiles(sSearchFolder, File, IO.SearchOption.AllDirectories).Any Then
sTargetFile = sFoundFiles
Else
sTargetFile = sOrphanedFiles
End If
IO.File.AppendAllText(sTargetFile, $"{File}{Environment.NewLine}")
End Sub)
End Sub
End Module
If I've misjudged the requirements, let me know and I'll update accordingly.
Explanations and comments in-line.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'I presume txtFileName.Text contains the full path including the file name
'I also presume that this text file contains only file names with extensions
Dim FilesInTextFile = System.IO.File.ReadAllLines(txtFileName.Text)
'Instead of accessing the Directory over and over, just get an array of all the files into memory
'This should be faster than searching the Directory structure one by one
'Replace <DirectoryPathToSearch> with the actual path of the Directory you want to search
Dim FilesInDirectory = IO.Directory.GetFiles("<DirectoryPathToSearch>", "*.*", IO.SearchOption.AllDirectories)
'We now have an array of full path and file names but we just need the file name for comparison
Dim FileNamesInDirectory = From p In FilesInDirectory
Select Path.GetFileName(p)
'A string builder is more efficient than reassigning a string with &= because a
'string build is mutable
Dim sbFound As New StringBuilder
Dim sbOrphan As New StringBuilder
'Instead of opening a file, writing to the file and closing the file
'in the loop, just append to the string builder
For Each f In FilesInTextFile
If FileNamesInDirectory.Contains(f) Then
sbFound.AppendLine(f)
Else
sbOrphan.AppendLine(f)
End If
Next
'After the loop write to the files just once.
'Replace the file path with the actual path you want to use
IO.File.AppendAllText("C:\FoundFiles.txt", sbFound.ToString)
IO.File.AppendAllText("C:\OrphanFiles.txt", sbOrphan.ToString)
End Sub

How to get file's path created by this code?

I'm using this code to save files in my app
Dim filePath = String.Format("image{0:yyyyMMddHHmmss}.png", DateTime.Now)
PictureBox1.Image.Save(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), (filePath)))
So now I have a textbox1 and I want to show the path of last saved image in it
how?
Regards,,,,
What I've done in the past is generate the path in one step and then use the generated variable to do the saving and to display.
So instead of:
Dim filePath = String.Format("image{0:yyyyMMddHHmmss}.png", DateTime.Now)
PictureBox1.Image.Save(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), (filePath)))
Try:
'Generate the Path
Dim path As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), String.Format("image{0:yyyyMMddHHmmss}.png", DateTime.Now))
'Save using the generated path
PictureBox1.Image.Save(path)
'Display the path
textbox1.Text = path
Thanks all I've done it successfully `
Dim filename As String = String.Format("image{0:yyyyMMddHHmmss}.png", DateTime.Now)
Dim filePath1 = (IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), (filename)))
Dim filePath2 = (IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ("RMSS")))
If IO.Directory.Exists(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), (" RMSS"))) = True Then
TextBox1.Text = filePath1
TextBox2.Text = filePath2 & "\" & filename
PictureBox1.Image.Save(filePath1)
My.Computer.FileSystem.MoveFile(TextBox1.Text, TextBox2.Text, True)
Else
TextBox1.Text = filePath1
TextBox2.Text = filePath2 & "\" & filename
PictureBox1.Image.Save(filePath1)
My.Computer.FileSystem.MoveFile(TextBox1.Text, TextBox2.Text, True)
End If