copy all files with certain extension - vb.net

Hello I want to copy all files with and a specific extension. I've tried a few things but it isn't working. During my debug I get an exception "Illegal characters used in path" I'm guessing it doesn't like *.xls any suggestions?
First try
My.Computer.FileSystem.CopyFile("C:\test\test\mxw\*.xls\", "C:\workorder1-23\workorder1-23\mxw\", True)
second try
For Each f In Directory.GetFiles("C:\test\test\mxw\*.xls\", CStr(SearchOption.AllDirectories))
If My.Computer.FileSystem.FileExists(f.ToString) Then
File.Copy("C:\test\test\mxw\*.xls\", "C:\workorder1-23\workorder1-23\mxw\", True)
End If
Next

CopyFile copies just one file.
You cannot use it with wildcards to copy a group of files. (The invalid character is probably the wildcard)
And you should not append a backslash at the end of the file.
So let me try to replace your code with this
For Each f In Directory.GetFiles("C:\test\test\mxw", "*.xls", SearchOption.AllDirectories)
If File.Exists(f) Then
File.Copy(f, Path.Combine("C:\workorder1-23\workorder1-23\mxw", Path.GetFileName(f)), True)
End If
Next
Also Directory.GetFiles has three parameters, a path, a pattern and a flag to read subfolders

Since File.Copy does not create directories the provided answer will only work if the target directories exist. Add a Create.Directory(f) before the File.Copy if they don't.

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.

VB.net FileSystem.rename - old path knowing only a substring

How can I rename a file that I don't know the full name, but I only know that it begin with a base string?
I must rename a file in a folder, that begins with a default string and then has extra unknow chars. I'm sure in that folder will be only one file beginning with that string.
It would be something like searching "string*.txt" and rename it with "string.txt", but FileSystem.rename doesn't accept oldPath with "*" as argument.
Dim _files as String() = IO.Directory.GetFiles("c:\temp\", "string*.txt")
IO.File.Move(_files(0), "c:\temp\newfilename.txt")
Still needs some checking if file found, etc. but this should work
You need to loop through all the files in your given directory, if one name matches then you know it's your file.
Structure of the code might look like this :
Function LookForName(Path As String) As String
'For Each File in your path
'If the name starts with "string" and ends with ".txt"
'You can return this filename
End Function
'You call LookForName with a given path
'You rename the returned file

Check if directory exists, but string is relative path

I am currently writing a program to check if hyperlinks in a file are broken. Some hyperlinks go directly to folders on a mapped drive.
I want to use dir() to check if the folder exists, but Excel shortens the string to the relative version "../../Random folder/Another random folder"
This string returns "" so my function thinks the folder does not exist, but it does and its link functions properly.
Any help is greatly appreciated.
Thanks!
I believe you need to use the overloaded function of Dir and specify vbDirectory as the additional argument. I believe it should look something like this:
If Dir("X:\random directory\other random directory", vbDirectory) = "" Then

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()

How to specify a path with spaces for StreamWriter

In VB.Net, how do I provide the StreamWriter constructor with a path that includes spaces? StreamWriter("""C:\Users\Public\Public Users\file.txt""") does not work.
Here is a working code example:
Dim fs As New System.IO.StreamWriter("e:\test 123.txt")
fs.Write("hello")
fs.Close()
UPDATE:
The new example for folder with space(s):
'this is your filename
Dim Filename As String = "e:\folder with space\test 123.txt"
'this is your folder
Dim Folderpath As String = System.IO.Path.GetDirectoryName(Filename)
'now do checking if the folder exists, if not create the folder
If System.IO.Directory.Exists(Folderpath) = False Then
System.IO.Directory.CreateDirectory(Folderpath)
End If
'now create the file as usual
Dim fs As New System.IO.StreamWriter("e:\folder with space\test 123.txt")
fs.Write("hello")
fs.Close()
The reason for your code didn't compile because you have not create the folder before creating the file, ie that folder must be existed before you can create your file.
You don't put quotes around the string you pass to the StreamReader constructor. Quotes are only used when you use, say, the command line. Or anything else that uses spaces as separators between arguments. The program requires those double quotes to recognize an argument with an embedded space.
Not necessary here, there's no ambiguity since the argument only takes the path to a single file. The only exception to that rule that I know of is the ProcessStartInfo.Arguments property.
So, just put single double quotes around the string, the syntax that the compiler requires. Your real problem is the name of the folder. Windows Explorer shows a different name for the folders in c:\users\public. For example c:\users\public\videos is displayed in the Explorer window as "Public Videos". It's trying to be helpful by expanding the abbreviated name. Your program however has to use the real folder name. Which is probably "users", not "Public Users". To find out for sure, use the command line (cmd.exe). Use cd \users\public and dir /a.
Last but not least, that folder has a different name on different versions of Windows. You should use Environment.GetFolderPath(). "Public Users" isn't a standard folder name however, not sure why you are using it.