Delete items within a folder rather than deleing the entire folder itself using vb.net - vb.net

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

Related

Delete A File That Contains The App Name (VB.NET)

This is the code I'm Using:
Dim file As String
Dim prefetchPath As String
Dim FileName As String = My.Application.Info.AssemblyName
prefetchPath = Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine) & "\Prefetch"
For Each file In IO.Directory.GetFiles(prefetchPath)
If file.Contains(FileName) Then
IO.File.Delete(file)
End If
Next
i don't know why it does not work if i use FileName. But it work if i use this code
If file.Contains("Example.exe") Then
IO.File.Delete(file)
End If
I want to make sure that if someone changes the name of the application the code works the same way(I already running the file as Administrator)
Help me Thanks.
My guess is that AssemblyName only returns the name without the extension, try including the .exe. Also, it is worth noting that you can use the IO.DirectoryInfo class and pass the file name in the GetFiles method to cut out your For/Each loop.
Here is a quick example:
Dim prefetchPath As String = IO.Path.Combine(Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine), "Prefetch")
Dim FileName As String = My.Application.Info.AssemblyName & ".exe"
If New IO.DirectoryInfo(prefetchPath).GetFiles(FileName).Count > 0 Then
IO.File.Delete(IO.Path.Combine(prefetchPath, FileName))
End If

Access vba Check if file exists

I have a database split in FrontEnd and BackEnd.
I have it running:
i) in my office
ii) updating/testing in my personal computer.
My BackEnd file is running in different Folder location according to computer running.
I want to place a code and check if file exist.
Code:
Sub FileExists()
Dim strPath As String '<== Office.
Dim strApplicationFolder As String
Dim strPathAdmin As String '<== Admin.
strPath = "\\iMac\Temp\"
strApplicationFolder = Application.CurrentProject.Path
strPathAdmin = strApplicationFolder & "\Temp\"
If Dir(strApplicationFolder & "SerialKey.txt") = "" Then
'===> Admin User.
If Dir(strPathAdmin & "*.*") = "" Then
'===> Empty Folder.
Else
'===> Files on folder.
End If
Else
'===> Office User.
If Dir(strPath & "*.*") = "" Then
'===> Empty Folder.
Else
'===> Files on folder.
End If
End If
End Sub()
I have this until now.
Any help.
Thank you...
Create a small function to check if a file exists and call it when needed.
Public Function FileExists(ByVal path_ As String) As Boolean
FileExists = (Len(Dir(path_)) > 0)
End Function
Since the backend database paths dont change, why dont you declare two constants and simply check their value?
Sub Exist()
Const workFolder As String = "C:\Work Folder\backend.accdb"
Const personalFolder As String = "D:\Personal Folder\backend.accdb"
If FileExists(workFolder) Then
'Work folder exists
End If
'....
If FileExists(personalFolder) Then
'Personal folder exists
End If
End Sub
This is a very belated reply, but don't reinvent the wheel. VBA can access the FileSystemObject, which includes a powerful set of methods that fetch file and folder information without requiring you to write your own functions, and the resulting code is much easier to read.
Second, borrowing on the previous answer, you know the folders you want the code to look at, and they don't change much, but because they could, I would also move your parameters into the declaration so they can be customized if needed or default to existing values.
Finally, FileExists is a verb, which should scream Function rather than Sub, so I'm guessing you want to return something and use it elsewhere in higher level code. It so happens that FileExists is already the name of a method in FileSystemObject, so I'm going to rename your function to LocatePath. You could return the valid path of the file you're looking for and decide by convention to quietly return an empty string "" if the target isn't found, and handle that in the calling procedure.
fs.BuildPath(strRootPath, strFileOrSubDir) appends strFileOrSubDir to strRootPath to construct a properly
formatted, full pathname and you don't need to worry about
whether you have backslashes (or too many) between the two.
It can be used to append files, or subdirectories, or
files in subdirectories.
fs.FileExists(strFullPath) is simple, returns True if strFullPath exists,
and False otherwise.
fs.GetFolder(strFolderName) returns a Folder object that has a
.Files property, which is a Collection object. Collection
objects in turn have a .Count property, which in this example
indicates how many files are in strFolderName. The Collection
object could also be used to iterate over all the files in the
folder individually.
What follows is your code refactored to incorporate all the changes I recommend according to what I think you're trying to achieve. It's not as symmetric as I'd like, but mirrors your code, and it's simple, easy to read, and finished in the sense that it does something.
Function LocatePath(Optional strWorkPath as String = "\\iMac",
Optional strHomePath as String = CurrentProject.Path,
Optional strFile as String = "SerialKey.txt"
Optional strSubDir as String = "Temp") as String
Dim fs as Object
Set fs = CreateObject("Scripting.FileSystemObject")
If fs.FileExists(fs.BuildPath(strHomePath, strFile)) Then
If fs.GetFolder(fs.BuildPath(strHomePath, strSubDir).Files.Count > 0 Then '===> Admin User.
LocatePath = fs.BuildPath(strHomePath, strFile)
ElseIf fs.GetFolder(fs.BuildPath(strWorkPath, strSubDir).Files.Count > 0 Then '===> Office User
LocatePath = fs.BuildPath(strWorkPath, strFile)
End If
Else 'Target conditions not found
LocatePath = ""
End If
Set fs = Nothing
End Function()
Ideally, I probably wouldn't specify strHomePath as String = CurrentProject.Path because strWorkPath as String = CurrentProject.Path is probably also true when you're at work, and you would want to do a better job of differentiating between the two environments. This is also what causes the little problem with symmetry that I mentioned.

VB Getting The SubFolder name and saving it to a Text file

I want to get The Subfolder Name Listed in my Textfile.
I don't want to see the path for the SubFolder.
I finally got a way to show only to my VS Console. But If i try to save it to my txt file it keeps on writing only the first line even though I used For. Please Help Me!
Here's the code that writes to the console
Dim di As New IO.DirectoryInfo(startPath)
Dim Drs() As IO.DirectoryInfo = di.GetDirectories()
For Each dr As IO.DirectoryInfo In Drs
Console.WriteLine(dr.Name)
Next
This is the code that I tried to Write It on a txt file. It only writes 1 Line
For Each Dir As String In Directory.GetDirectories(startPath)
My.Computer.FileSystem.WriteAllText("C:\Test.txt", Dir, False)
Next
The Expected Output is
SubFolder1
SubFolder2
SubFolder3
SubFolder4
SubFolder5
Like this in txt file
You are using the wrong method, WriteAllText always overwrites the complete file, you want to append a new line. You could use File.AppendAllText:
For Each Dir As String In Directory.GetDirectories(startPath)
System.IO.File.AppendAllText("C:\Test.txt", Dir)
Next
Another option, use a StreamWriter, it has a constructor that takes a Boolean to append text:
Using writer As New System.IO.StreamWriter(startPath, True)
For Each Dir As String In Directory.GetDirectories(startPath)
writer.WriteLine(Dir)
Next
End Using

VB.NET - Rename all the folders (And sub folders) in a selected folder

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

How to get the file name of a file in VB?

I make a search program for searching a list of files in a computer and then copy the file into a store folder. The file name could be "*11*2.txt" As long as the program find this pattern, it should copy to the store folder. The problem is that I don't know the exactly name of the file before the search and I don't want to rename the file, I don't know how to save the file. Please help
I use the following to find the file, which does its work
Public Sub DirSearch(ByVal sDir As String, ByVal FileName As String)
Dim To_Path As String
To_Path = Form1.TextBox5.Text
For Each foundFile As String In My.Computer.FileSystem.GetFiles(sDir, FileIO.SearchOption.SearchAllSubDirectories, FileName)
Copy2Local(foundFile, To_Path)
Next
End Sub
Here is the current version of the Copy2Local (Note: it is not working right)
Public Sub Copy2Local(ByVal Copy_From_Path As String, ByVal Copy_To_Path As String)
' Specify the directories you want to manipulate.
Try
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
' Copy the file.
File.Copy(Copy_From_Path, Copy_To_Path)
Catch
End Try
End Sub
First, you should check if ToPath is a valid directory since it's coming from a TextBox:
Dim isValidDir = Directory.Exists(ToPath)
Second, you can use Path.Combine to create a path from separate (sub)directories or file-names:
Dim copyToDir = Path.GetDirectoryName(Copy_To_Path)
Dim file = Path.GetFileName(Copy_From_Path)
Dim newPath = Path.Combine(copyToDir, file)
http://msdn.microsoft.com/en-us/library/system.io.path.aspx
(disclaimer: typed from a mobile)
To answer your question: You can get the file name with Path.GetFileName. Example:
Dim fileName As String = Path.GetFileName(foundFile)
However, there's a bunch of other things wrong with your code:
Here,
Dim fs As FileStream = File.Create(Copy_From_Path)
fs.Close()
you are overwriting your source file. This does not seem like a good idea. ;-)
And here,
Try
...
Catch
' Do Nothing
End Try
You are throwing away exceptions that would help you find and diagnose problems. Don't do that. It makes debugging a nightmare.
In vb.net, I'm using the following code to find the filename
Textbox1.Text = New FileInfo(OpenFileDialog.FileName).Name
this code work fine with open file dialog box