How do I create a folder in VB if it doesn't exist? - vb.net

I wrote myself a little downloading application so that I could easily grab a set of files from my server and put them all onto a new pc with a clean install of Windows, without actually going on the net. Unfortunately I'm having problems creating the folder I want to put them in and am unsure how to go about it.
I want my program to download the apps to program files\any name here\
So basically I need a function that checks if a folder exists, and if it doesn't it creates it.

If Not System.IO.Directory.Exists(YourPath) Then
System.IO.Directory.CreateDirectory(YourPath)
End If

Under System.IO, there is a class called Directory.
Do the following:
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
End If
It will ensure that the directory is there.

Try the System.IO.DirectoryInfo class.
The sample from MSDN:
Imports System
Imports System.IO
Public Class Test
Public Shared Sub Main()
' Specify the directories you want to manipulate.
Dim di As DirectoryInfo = New DirectoryInfo("c:\MyDir")
Try
' Determine whether the directory exists.
If di.Exists Then
' Indicate that it already exists.
Console.WriteLine("That path exists already.")
Return
End If
' Try to create the directory.
di.Create()
Console.WriteLine("The directory was created successfully.")
' Delete the directory.
di.Delete()
Console.WriteLine("The directory was deleted successfully.")
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
End Sub
End Class

Since the question didn't specify .NET, this should work in VBScript or VB6.
Dim objFSO, strFolder
strFolder = "C:\Temp"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists(strFolder) Then
objFSO.CreateFolder strFolder
End If

Try this: Directory.Exists(TheFolderName) and Directory.CreateDirectory(TheFolderName)
(You may need: Imports System.IO)

VB.NET? System.IO.Directory.Exists(string path)

Directory.CreateDirectory() should do it.
http://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory(VS.71).aspx
Also, in Vista, you probably cannot write into C: directly unless you run it as an admin, so you might just want to bypass that and create the dir you want in a sub-dir of C: (which i'd say is a good practice to be followed anyways. -- its unbelievable how many people just dump crap onto C:
Hope that helps.

(imports System.IO)
if Not Directory.Exists(Path) then
Directory.CreateDirectory(Path)
end if

If Not Directory.Exists(somePath) then
Directory.CreateDirectory(somePath)
End If

You should try using the File System Object or FSO. There are many methods belonging to this object that check if folders exist as well as creating new folders.

I see how this would work, what would be the process to create a dialog box that allows the user name the folder and place it where you want to.
Cheers

Just do this:
Dim sPath As String = "Folder path here"
If (My.Computer.FileSystem.DirectoryExists(sPath) = False) Then
My.Computer.FileSystem.CreateDirectory(sPath + "/<Folder name>")
Else
'Something else happens, because the folder exists
End If
I declared the folder path as a String (sPath) so that way if you do use it multiple times it can be changed easily but also it can be changed through the program itself.
Hope it helps!
-nfell2009

Related

How to extract a zip file to directory and overwrite?

I made a little program that downloads a .zip file from my website and then later it installs in a specific directory. It works fine unless a file with the same name already exists, then I get an error. This is the code I have.
If Form1.CheckBox1.Checked = True Then
Label4.Text = "Downloading Test File!"
wc.DownloadFileAsync(New Uri("http://www.example.com/TestFile.zip"), Directory + "\TestFile.zip")
While wc.IsBusy = True
Application.DoEvents()
End While
ListBox1.Items.Add("Test File")
End If
'Install
If Form1.CheckBox1.Checked = True Then
ZipFile.ExtractToDirectory(Directory + "\TestFile.zip", Directory_Select.TextBox1.Text)
ListBox2.Items.Add("Test File")
End If
So for example, if the files inside "TestFile.zip" have the same name as Install location, it will give me following error:
The file 'filePath` already exists.
It doesn't finish extracting because a file with the same name already exists. Deleting the file beforehand is not a good solution because there will be multiple files with the same name.
How can I replace while extracting?
Also is there a way to pause the program till the file finishes extracting since some files are large and it takes some time before they are extracted.
Thanks in advance for helping me out, I am new and still learning. Appreciate your help.
Although the ExtractToDirectory method doesn't support overwriting files by default, the ExtractToFile method has an overload which takes a second boolean variable that allows you to overwrite the file being extracted. What you can do is to iterate over the files inside the archive and extract them one by one using ExtractToFile(filePath, True).
I have created an extension method which does just that and have been using it for a while. Hope you find it useful!
Add the following module to your project:
Module ZipArchiveExtensions
<System.Runtime.CompilerServices.Extension>
Public Sub ExtractToDirectory(archive As ZipArchive,
destinationDirPath As String, overwrite As Boolean)
If Not overwrite Then
' Use the original method.
archive.ExtractToDirectory(destinationDirPath)
Exit Sub
End If
For Each entry As ZipArchiveEntry In archive.Entries
Dim fullPath As String = Path.Combine(destinationDirPath, entry.FullName)
' If it's a directory, it doesn't have a "Name".
If String.IsNullOrEmpty(entry.Name) Then
Directory.CreateDirectory(Path.GetDirectoryName(fullPath))
Else
entry.ExtractToFile(fullPath, True)
End If
Next entry
End Sub
End Module
Usage:
Using archive = ZipFile.OpenRead(archiveFilePath)
archive.ExtractToDirectory(destPath, True)
End Using
Side note: Don't concatenate strings to form a path out of its parts; use Path.Combine() instead.

Visual Basic don't see application.evtx

I have a problem with "Application.evtx" file. Everytime I run my script I get the message box with "File not found" information and I don't know why. I ran Visual Studio as administrator. Help me with this one, please.
Imports System.IO
Module Module1
Sub Main()
Dim pathReadFile As String = "c:\Windows\System32\winevt\Logs\Application.evtx"
'Dim pathReadFile As String = "%windir%\Sysnative\winevt\Logs\Application.evtx"
'Dim pathReadFile As String = "D:\Dokumenty\MyTest.txt"
Try
If File.Exists(pathReadFile) Then
MsgBox("File found.")
Else
MsgBox("File not found.")
End If
Catch ex As Exception
End Try
End Sub
End Module
Don't use File.Exists(). Ever.
There are many reasons for this, but the one that impacts you right now is that it lies to you and tells you the file does not exist, even if the file actually does exist and the real problem is that you don't have permissions to use it. From the docs:
Return Value
Type: System.Boolean
true if the caller has the required permissions and path contains the name of an existing file; otherwise, false
Remember that normal users have extremely limited file system permissions outside of their own home folders, and even Administrator users need to explicitly run a process as elevated or UAC will just give them normal user permissions.
You have to handle the exception anyway if reading the file fails. Put your development effort into the exception handler.
While I'm here, you may also want to build your path like this:
Dim pathReadFile As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "winevt\Logs\Application.evtx")

Visual Basic FileSystem.GetFiles

I'm making a console application and I want to see what files is in a folder
For Each foundFile As String In My.Computer.FileSystem.GetFiles("c:\users\zac\desktop\booked vehicle\requested\")
Console.WriteLine(foundFile)
Next
after using this code and find that the folder is empty I need an If statement that say's
If foundfile has no files then
tell user no files found
end if
but I don't know how to write this so Visual Basic understands.
Load the files into a variable then check the count.
Dim files = My.Computer.FileSystem.GetFiles("c:\users\zac\desktop\booked vehicle\requested\")
If files.Count = 0 Then
'tell user no files
Else
For Each file In files
Console.WriteLine(file)
Next
End If
FileSystem.GetFiles() returns a collection of file name strings. As OneFineDay showed, you can use the collection's Count property to know if any files were found.
The downside of using FileSystem.GetFile() is that it has to search the entire folder before then returning the entire list of filenames. If you are searching large folders and speed is an issue, consider using Directory.EnumerateFiles() instead. That way, you can output a message if no file was found, otherwise loop throuh the list of found files. For example:
Dim files = Directory.EnumerateFiles("c:\users\zac\desktop\booked vehicle\requested\").GetEnumerator()
If files.MoveNext Then
' files were found
Do
Console.WriteLine(files.Current)
Loop Until Not files.MoveNext
Else
' no files were found
End If
I personally would use Linq to accomplish this. It's very quick and efficient to use in this case. I put the Console.ReadLine() at the end to show the files, you can remove this if need to be. Also you can change the Console.WriteLine to not include the string (s) if you don't want to. The s was declared if you want to show the files and also to see if there are any files. As I said, this was for my viewing to see the files. Straight to the point!
Dim s As String = String.Join(Environment.NewLine, New DirectoryInfo("YOUR DIRECTORY").GetFiles().[Select](Function(file) file.Name).ToArray)
Console.WriteLine(If(s.Length > 0, s, "No files found!"))
Console.ReadLine()

Making folder and copying file

I want my application to look for a file in drive C's specific folder (say C:\myFolder\abc.mdb), if found just give a message if not, make the folder in drive C:\ and then copy the file.
How to do this?
Thanks
Furqan
You could use the File, Directory, and Path objects in the System.IO as shown below:
Imports System.IO
...
Dim path As String = "C:\myFolder\abc.mdb"
If File.Exists(path) Then
'TODO write code to create message'
Else
Dim folder As String = Path.GetDirectoryName(path)
If Not Directory.Exists(folder) then
Directory.CreateDirectory(folder)
End If
'TODO code to copy file from current location to the newly created directory path'
'i.e. File.Copy(FileToCopy, NewCopy)'
End If
I know this post is kind of old. I just wanted to update.
The quickest shortcut that will also create the Destination directory structure and in one line. Use Computer.FileSystem.CopyFile instead of System.IO.
My.Computer.FileSystem.CopyFile(sSourcefile, sDestinationfile)

Deleting a file in VBA

Using VBA, how can I:
test whether a file exists, and if so,
delete it?
1.) Check here. Basically do this:
Function FileExists(ByVal FileToTest As String) As Boolean
FileExists = (Dir(FileToTest) <> "")
End Function
I'll leave it to you to figure out the various error handling needed but these are among the error handling things I'd be considering:
Check for an empty string being passed.
Check for a string containing characters illegal in a file name/path
2.) How To Delete a File. Look at this. Basically use the Kill command but you need to allow for the possibility of a file being read-only. Here's a function for you:
Sub DeleteFile(ByVal FileToDelete As String)
If FileExists(FileToDelete) Then 'See above
' First remove readonly attribute, if set
SetAttr FileToDelete, vbNormal
' Then delete the file
Kill FileToDelete
End If
End Sub
Again, I'll leave the error handling to you and again these are the things I'd consider:
Should this behave differently for a directory vs. a file? Should a user have to explicitly have to indicate they want to delete a directory?
Do you want the code to automatically reset the read-only attribute or should the user be given some sort of indication that the read-only attribute is set?
EDIT: Marking this answer as community wiki so anyone can modify it if need be.
An alternative way to code Brettski's answer, with which I otherwise agree entirely, might be
With New FileSystemObject
If .FileExists(yourFilePath) Then
.DeleteFile yourFilepath
End If
End With
Same effect but fewer (well, none at all) variable declarations.
The FileSystemObject is a really useful tool and well worth getting friendly with. Apart from anything else, for text file writing it can actually sometimes be faster than the legacy alternative, which may surprise a few people. (In my experience at least, YMMV).
I'll probably get flamed for this, but what is the point of testing for existence if you are just going to delete it? One of my major pet peeves is an app throwing an error dialog with something like "Could not delete file, it does not exist!"
On Error Resume Next
aFile = "c:\file_to_delete.txt"
Kill aFile
On Error Goto 0
return Len(Dir$(aFile)) > 0 ' Make sure it actually got deleted.
If the file doesn't exist in the first place, mission accomplished!
The following can be used to test for the existence of a file, and then to delete it.
Dim aFile As String
aFile = "c:\file_to_delete.txt"
If Len(Dir$(aFile)) > 0 Then
Kill aFile
End If
In VB its normally Dir to find the directory of the file. If it's not blank then it exists and then use Kill to get rid of the file.
test = Dir(Filename)
If Not test = "" Then
Kill (Filename)
End If
set a reference to the Scripting.Runtime library and then use the FileSystemObject:
Dim fso as New FileSystemObject, aFile as File
if (fso.FileExists("PathToFile")) then
aFile = fso.GetFile("PathToFile")
aFile.Delete
End if
Here's a tip: are you re-using the file name, or planning to do something that requires the deletion immediately?
No?
You can get VBA to fire the command DEL "C:\TEMP\scratchpad.txt" /F from the command prompt asynchronously using VBA.Shell:
Shell "DEL " & chr(34) & strPath & chr(34) & " /F ", vbHide
Note the double-quotes (ASCII character 34) around the filename: I'm assuming that you've got a network path, or a long file name containing spaces.
If it's a big file, or it's on a slow network connection, fire-and-forget is the way to go.
Of course, you never get to see if this worked or not; but you resume your VBA immediately, and there are times when this is better than waiting for the network.
You can set a reference to the Scripting.Runtime library and then use the FileSystemObject. It has a DeleteFile method and a FileExists method.
See the MSDN article here.
A shorter version of the first solution that worked for me:
Sub DeleteFile(ByVal FileToDelete As String)
If (Dir(FileToDelete) <> "") Then
' First remove readonly attribute, if set
SetAttr FileToDelete, vbNormal
' Then delete the file
Kill FileToDelete
End If
End Sub