I have a directorry which contains many folders such as folder1,folder2,folder3 etc..which contains sub-directories..In that I have a folder name "special" which contains some files
Now I would like to get all those files based on the name of the sub-directory
Example:
C:\Users\desktop\Myfolder\folder1\special\
C:\Users\desktop\Myfolder\folder2\special\
C:\Users\desktop\Myfolder\folder3\special\
C:\Users\desktop\Myfolder\folder4\special\
Now I need to get all the files from each special folder of all the folder1,folder2,folder3 and folder4 and display them in gridview.
grid1.DataSource = (From p1 In IO.Directory.GetFiles("C:\Users\desktop\Myfolder\", "*", IO.SearchOption.AllDirectories)
Where p1.Contains("\special\"))
grid1.DataBind()
I just worked on your case, and i think the following piece of code will suits your requirement. The given code will drill through the directories and it display the filenames if it is comes under the special directory. Comment me back if i wrongly answered your question.
The procedure,
Private Sub GetFiles(ByVal xPath As String)
Try
If Directory.GetDirectories(xPath).Length > 0 Then
For Each xDir As String In Directory.GetDirectories(xPath)
If Directory.Exists(xDir) Then
GetFiles(xDir)
End If
Next
End If
If Directory.GetFiles(xPath).Length > 0 Then
For Each xDir As String In Directory.GetFiles(xPath)
If UCase(Path.GetDirectoryName(xDir)).EndsWith("SPECIAL") Then
MsgBox(Path.GetFileName(xDir))
End If
Next
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
and the call,
call GetFiles("D:\test")
if your datagridview is datagridview1 and countains two columns and you want to add the name file and last modified here is the solution ..
For Each sDir In Directory.GetDirectories("C:\Users\desktop\Myfolder\", "special", SearchOption.AllDirectories)
For Each File In Directory.GetFiles(sDir)
Dim detailedfile As New IO.FileInfo(File)
DataGridView1.Rows.Add(detailedfile.Name, detailedfile.LastAccessTime)
Next
next
if you want to add more details in the gridview you have just to add more columns and more integers in the DataGridView1.Rows.Add
Related
I want to delete all the files contained in a folder. The below code does delete the file but also deletes the folder itself. I am aware you will need to perform a for loop to remove each item from the folder, but can't find the information on how to start the code for it. Can someone point me in the correct direction.
Dim folderFiles() As String
folderFiles= Directory.GetFileSystemEntries("C:\New Folder")
For Each element As String In files
If (Not Directory.Exists(folder)) Then
File.Delete(Path.Combine("C:\New Folder", Path.GetFileName(folder)))
End If
Next
This is the easier way :
For Each the_file As String In Directory.GetFileSystemEntries("C:\New folder")
File.Delete(the_file)
Next
Don't bother to grab the list of files and then browse it, use your loop directly on it.
I have a function for that. With it, you can also delete all files of a pattern even for all subdirectories:
Public Sub DeleteFiles(Path As String,
Optional Pattern As String = "*.*",
Optional All As Boolean = False)
Dim SO As IO.SearchOption = If(All, IO.SearchOption.AllDirectories, IO.SearchOption.TopDirectoryOnly)
For Each Filename As String In Directory.GetFiles(Path, Pattern, SO)
File.Delete(Filename)
Next
End Sub
So you could use it for your task like:
DeleteFiles("C:\New Folder")
I would use this code
For Each file As String In IO.Directory.GetFiles("the path")
IO.File.Delete(file)
Next
This deletes everything in the folder but not the folder itself.
This is quick and easy, especially if 1) there's nothing special about the folder, eg permissions, and 2) the folder might contain sub-folders, sub-sub-folders, etc.
Simply delete the original folder and recreate it:
Dim path As String = {your path}
IO.Directory.Delete(path, recursive:=True)
IO.Directory.CreateDirectory(path)
Another option for folders with sub-folders where you wish to keep the (empty) sub-folders, is to use recursion:
Sub EmptyFolder(path As String) As Boolean
Try
For Each dir As String In IO.Directory.GetDirectories(path)
EmptyFolder(dir)
Next dir
For Each file As String In IO.Directory.GetFiles(path)
IO.File.Delete(file)
Next file
Catch
Throw
End Try
End Function
I'm fairly familiar with bash, but I'm very, ***very**** new to vb.net. I'm searching for an easy way to find files in a folder that end with .G1, .G2, .G3, etc. but NOT .GP1, .GP2, .GP3, etc. Then for each file I need to copy it to another folder using a different file name but the same extension. I've managed to figure this out for the unique files, but there will be an undefined number of these depending on the project and I need to make sure that I get them all. Hard coding is possible, but very, very ugly. Any suggestions?
Here's the remnants of a failed attempt:
Public Sub FindGFiles()
FileList = IO.Directory.GetFiles(searchDir, ".G[1-99]" + , IO.SearchOption.AllDirectories)
For Each foundfile As String In FileList
If foundfile.Contains(".G#") Then
'copy file somehow and retain file extension
Else
MsgBox("No match")
End If
Next
End Sub
The GetFiles-method does only support * and ? wildcard characters.
So you have to get all files with a *.G*-extension first.
In the For Each-loop one can then use the Like-operator to check the desired pattern:
Public Sub CopyGFiles(searchDir As String, destDir As String)
Dim fileList As String() = IO.Directory.GetFiles(searchDir, "*.G*", IO.SearchOption.AllDirectories)
Dim fileName As String
Dim extension As String
For Each foundfile As String In fileList
fileName = IO.Path.GetFileNameWithoutExtension(foundfile)
extension = IO.Path.GetExtension(foundfile)
If extension Like ".G#" OrElse
extension Like ".G##" Then
'copy file to destination, append "_new" to the filename and retain file extension
IO.File.Copy(foundfile, IO.Path.Combine(destDir, fileName & "_new" & extension))
Else
'pattern not matched
End If
Next
End Sub
The method-call would then be as follows:
CopyGFiles("C:\Temp", "C:\Temp\Dest")
This should be done inside a Try/Catch as different exceptions can occur when working with files.
Try
CopyGFiles("C:\Temp", "C:\Temp\Dest")
Catch ex As Exception
MessageBox.Show("An error occured" + vbCrLf + ex.Message)
End Try
So I've been working on a program that will find all files from a directory and subdirectories and my application is "freezing" while executing because its single-threaded, but I don't know how to multithread a function with an argument in it. so the use is like getallfiles("C:/Folder") and after this it will add each file in a listbox using the following code.
Private Sub getallfiles(filelocation As String)
Try
For Each item As String In My.Computer.FileSystem.GetFiles(filelocation)
If Path.GetExtension(item) = My.Settings.scanfor & "filter" Then
Me.Invoke(Sub() ListBox1.Items.Add(item))
Me.Invoke(Sub() ListBox1.SelectedIndex = ListBox1.Items.Count - 1)
End If
Next
For Each folder As String In My.Computer.FileSystem.GetDirectories(filelocation)
Me.Invoke(Sub() getallfiles(folder))
Next
Catch ex As Exception
End Try
End Sub
and I'm trying to use Thread1 = New System.Threading.Thread(AddressOf getcache(item))
Error BC30577 'AddressOf' operand must be the name of a method
(without parentheses).
if you know any ways of fixing or doing this, I would be happy to hear your answer
Instead of using the vb file functions try the .net System.IO functions. With Directory.GetFiles("Path of Directory to search", "*.txt", SearchOption.AllDirectories) you can search with an extension filter as the second parameter and the last parameter will search all sub-directories. Don't add your items one by one to the listbox. That would be very slow because the listbox has to redraw on each iteration. The GetFiles function returns an array of Strings. You can add this all at once with the listbox items .AddRange Don't forget to add Imports System.IO at the top of the file.
https://msdn.microsoft.com/en-us/library/ms143316(v=vs.110).aspx
Dim FilesFromDir() As String = Directory.GetFiles("C:\Users\maryo\Documents\TextNotes", "*.txt", SearchOption.AllDirectories)
ListBox3.Items.AddRange(FilesFromDir)
I'm creating a VB project for Quiz App (in VS 2013). So I have some preset questions which are inside the project (I have created a folder inside my project and added a text file).
My question is how can I read and write contents to that file? Or if not is there any way to copy that txt file to Documents/MyAppname when installing the app so that I can edit it from that location?
In the example below I am focusing on accessing files one folder under the executable folder, not in another folder else wheres. Files are read if they exists and then depending on the first character on each line upper or lower case the line then save data back to the same file. Of course there are many ways to work with files, this is but one.
The following, created in the project folder in Solution Explorer a folder named Files, add to text files, textfile1.txt and textfile2.txt. Place several non empty lines in each with each line starting with a character. Each textfile, set in properties under solution explorer Copy to Output Directory to "Copy if newer".
Hopefully this is in tune with what you want. It may or may not work as expected via ClickOnce as I don't use ClickOnce to validate this.
In a form, one button with the following code.
Public Class Form1
Private TextFilePath As String =
IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "Files")
Private TextFiles As New List(Of String) From
{
"TextFile1.txt",
"TextFile2.txt",
"TextFile3.txt"
}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileName As String = ""
' loop thru each file
For Each fileBaseName As String In TextFiles
FileName = IO.Path.Combine(TextFilePath, fileBaseName)
' only access file if it exist currently
If IO.File.Exists(FileName) Then
' read file into string array
Dim contents As String() = IO.File.ReadAllLines(FileName)
' upper or lower case line based on first char.
' this means you can flip flop on each click on the button
For x As Integer = 0 To contents.Count - 1
If Char.IsUpper(CChar(contents(x))) Then
contents(x) = contents(x).ToLower
Else
contents(x) = contents(x).ToUpper
End If
Next
' save changes, being pesstimistic so we use a try-catch
Try
IO.File.WriteAllLines(FileName, contents)
Catch ex As Exception
Console.WriteLine("Attempted to save {0} failed. Error: {1}",
FileName,
ex.Message)
End Try
Else
Console.WriteLine("Does not exists {0}", FileName)
End If
Next
End Sub
End Class
This may help you
Dim objStreamReader As StreamReader
Dim strLine As String
'Pass the file path and the file name to the StreamReader constructor.
objStreamReader = New StreamReader("C:\Boot.ini")
'Read the first line of text.
strLine = objStreamReader.ReadLine
'Continue to read until you reach the end of the file.
Do While Not strLine Is Nothing
'Write the line to the Console window.
Console.WriteLine(strLine)
'Read the next line.
strLine = objStreamReader.ReadLine
Loop
'Close the file.
objStreamReader.Close()
Console.ReadLine()
You can also check this link.
I tried to practise, search and i didn't find a solution to how to rename all the folders and sub-folders in a desired folder. For example i want to loop trough all the folders and add "_test" to the end, i searched, practiced and i didn't find any great solution so i'm asking to you if you have any snippet of code, or just and idea. I started with creating an array of all the folders within a folder by doing that:
Dim folderArray() As String = IO.Directory.GetDirectories(TextBoxPath.Text, "*", IO.SearchOption.AllDirectories)
For Each folder In folderArray
Dim infoParent As New IO.DirectoryInfo(folder)
Dim folderParent = infoParent.Parent.FullName
Dim folderName = folder.Split(IO.Path.DirectorySeparatorChar).Last()
FileSystem.Rename(folder, folderParent & "\" & folderName & "_Test")
Next
But that's not working, because i rename the directories, so the array is not valid (folderArray) because it has the old directory path.
If you have a way to do it, i'm opened to suggestions, thanks.
I would try do it recursively to make sure it's done at the bottom-most level first. (might not be 100% correct code, but just to give the general idea)
Sub RenameFolderRecursive(path As String)
For Each f As String In IO.Directory.GetDirectories(path)
RenameFolderRecursive(f)
Next
IO.Directory.Move(path, path & "_test")
End Sub
See if that works.
This sounds like a job for recursion. Since you don't know how many folders any given folder will contain, or how many levels deep a folder structure can be, you can't just loop through it. Instead, write a function which solves a discrete piece of the overall problem and recurse that function. My VB is very rusty so this might not be 100% valid (you'll definitely want to debug it a bit), but the idea is something like this:
Function RenameFolderAndSubFolders(ByVal folder as String)
' Get the sub-folders of the current folder
Dim subFolders() As String = IO.Directory.GetDirectories(folder, "*", IO.SearchOption.AllDirectories)
If subFolders.Length < 1 Then
'This is a leaf node, rename it and return
FileSystem.Rename(folder, folder & "_Test")
Return
End If
' Recurse on all the sub-folders
For Each subFolder in subFolders
RenameFolderAndSubFolders(subFolder)
' Rename the current folder once the recursion is done
FileSystem.Rename(subFolder, subFolder & "_Test")
Next
End Function
The idea here is simple. Given a folder name, get all of the child folders. If there aren't any, rename that folder. If there are, recurse the same function on them. This should find all of the folders and rename them accordingly. To kick off the process, just call the function on the root folder of the directory tree you want renamed.
Sub RenameAll(ByVal sDir As String)
Try
For Each d As String In Directory.GetDirectories(sDir)
IO.Directory.Move(d, d & "_test")
RenameAll(d & "_test")
Next
Catch x As System.Exception
End Try
End Sub
Here is recursive function that might do the job you need.
Private Sub RenameAllFolds(d As String)
Dim subfolds() As String = IO.Directory.GetDirectories(d)
If subfolds.Count = 0 Then
IO.Directory.Move(d, d & "_Test")
Else
For Each dir As String In subfolds
RenameAllFolds(dir)
Next
IO.Directory.Move(d, d & "_Test")
End If
End Sub
Sub Main()
Dim inf As String = "C:\renametest"
Dim folds() As String = IO.Directory.GetDirectories(inf)
For Each f As String In folds
RenameAllFolds(f)
Next
Console.ReadKey()
End Sub