vb.net wildcard file search exception - vb.net

im totally new to vb.net
I figured how to find files using wildcard and it works fine but i need error meassage if file not found.
here's my code.
any help highly appreciated !
For Each hist In Directory.GetFiles("C:\temp", "*.*", SearchOption.TopDirectoryOnly)
If File.Exists(hist) Then
File.Copy(hist, Path.Combine("C:\temp\1", Path.GetFileName(hist)), True)
MessageBox.Show("file exist and copied") <-- this message shows up and files are copied
Else
MessageBox.Show("No files. Folder is empty !") <--this message never shows up when folder is empty . no files at all
End If
Next

It is unlikely you would see that second message. You are grabbing the list of files from the OS directly - so, at least at the time that you retrieve the file name that file exists. If you wanted to simulate a case where the file doesn't exist, place a break point on the IF File.Exists(hist) Then line. While the program is paused there, go find and delete whatever the current file is. Then continue the program.

i got it working.
here's what i added before foreach :
Dim myDir As DirectoryInfo = New DirectoryInfo("c:\temp\")
If (myDir.EnumerateFiles().Any()) Then
foreach ....
else
MessageBox.Show("no files in directory ") <-- my message
thanks for advice!!

Related

Visual basic write in an opened file (printLine)

So I want to do this:
Open file "this.txt"
Write a line to this file (replacing anything else written to this file)
[Other stuff, irrelevant to the file]
Write a line to this file (replacing anything else written to this file)
Close the file
I thought it would be easy, but I was wrong. I tried many ways, but they all failed. Either they wouldn't let me write in an open file, or they would open the file and immediately close it (WriteAllText).
I ended up using FileOpen(), PrintLine() and FileClose() which lets me write in an open file but PrintLine only writes a new line, it doesn't replace everything in the file. Any help? Either with the printline or the whole thing
It is crucial that the file stays open until the very last moment I want it closed, (cause I have another program checking to see when this file is not open/used).
If this is about VB.NET, then you can use File.Open() with mode = FileMode.Truncate. This clears the file on opening. This assumes that the file exists.
You can also use SetLength() to truncate:
Dim f As FileStream
' FileMode.Truncate also works, but the file needs to exist from before
f = File.Open("test.txt", FileMode.OpenOrCreate, FileAccess.Write)
f.SetLength(0) ' truncate to zero size
Dim line As String = "hello2"
Dim w = New StreamWriter(f)
w.WriteLine(line)
w.Flush()
w.Close()
f.Close()
If this is about VB6, check out this question. One solution there is to import and use a native Windows function that does truncation.
In VB.Net OpenTextFileWriter does exactly what you need (docs):
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", False)
file.WriteLine("Here is the first string.")
file.Close()

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.

The filename 'filename' already exists VB .NET

I want to extract archive.
But the problem is, when the code runs, it throws the exception below:
System.IO.IOException: 'The file 'filename' already exists.'
Here are the code
File.WriteAllBytes(String_TempDir & "\rzip.zip", My.Resources.Resszip) 'I wrote the file from my application resources
Compression.ZipFile.ExtractToDirectory(String_TempDir & "\rzip.zip", String_TempDir) 'This line throws the exception
File.Delete(String_TempDir & "\rzip.zip")
I saw nothing(no file) before that code executed...
After the code executed, It throws the exception, but, my archived file has been extracted.
I used Try statement to distinguish the exception but it's still throwing that exception...
Try
Compression.ZipFile.ExtractToDirectory(String_TempDir & "\rzip.zip", String_TempDir)
Catch ex As IOException
'That's it.
End Try
The String_TempDir is a string which I assign it with:
'global declaration:
Dim folder As String = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)
'End of global declaration
Public Function GetTempDir() As String
Do While Directory.Exists(folder) Or File.Exists(folder)
folder = Path.Combine(Path.GetTempPath, Path.GetRandomFileName)
Loop
Return folder
End Function
'Form loads
Directory.CreateDirectory(folder)
String_TempDir = folder
Just guessing, but it could be that you are putting the Zip file into the same directory you are extracting to. Try extracting to a subdirectory of your temp directory. e.g.
Compression.ZipFile.ExtractToDirectory(String_TempDir & "\rzip.zip", String_TempDir & "\extracted")
The MSDN article on ExtractToDirectory says the following (emphasis mine):
This method creates the specified directory and all subdirectories.
The destination directory cannot already exist. Exceptions related to
validating the paths in the destinationDirectoryName or
sourceArchiveFileName parameters are thrown before extraction.
Otherwise, if an error occurs during extraction, the archive remains
partially extracted. Each extracted file has the same relative path to
the directory specified by destinationDirectoryName as its source
entry has to the root of the archive.
Have you also checked that the Zip file doesn't contain any duplicate names?
If it was compressed on Linux, it might have both Filename and filename inside it, and that might cause this error. Especially since you say that it doesn't contain any files at first and that it seems that it succeeds in decompressing it.
Somewhat similar question here, but with 7-Zip

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

the process cannot access the file because it is being used by another process in vb.net

help me.. i'm new in visual basic....
when i'm running the update it shows the error
The process cannot access the file 'C:\Documents and Settings\Macky\My Documents\Visual Studio 2008\Projects\Marcelo 2.2.3\Marcelo\bin\Debug\Students\MIC953867.jpg' because it is being used by another process.
my code is this
Public Sub copingfile()
If inFileName = Nothing Then
studpic.Image = Nothing
Else
outFileName = inFileName
pos = inFileName.LastIndexOf(".")
If (pos > 0) Then
outFileName = outFileName.Substring(0, pos)
End If
outFileName += ".jpg"
str = Application.StartupPath & "\Students\"
saveJPEGFile.FileName = str & StudID.Text & ".jpg" '& outFileName
fil1.Copy(inFileName, saveJPEGFile.FileName, True) 'the error shows here...
outFileName = saveJPEGFile.FileName()
End If
End Sub
I can save new student information with picture.. but when it comes in updating the picture these codes didn't work......
fil1.Copy(inFileName, saveJPEGFile.FileName, True)
You're attempting overwrite a file that's open or being used. If the file is open in a viewer/editor, then it can't be copied over. Either you opened it manually, or did so through code and it's still "attached" to something running.
If it's not open in a window, try stopping your code and deleting that file manually. If you can, it's pretty obvious something in code is still using it when you get to the line that errored. You'll need to figure out where that file is still being used (Open stream somewhere? Open in VS, itself?), as it doesn't appear to be in the code you provided.
You are going to need to show more code, you are using variables not in your code listing. Plus you do not show the code that originally saves your image.
But here is my guess...are you sure you closed the file when you saved it for the first time? You cannot generally copy to, or from, a file that is open.
(Files can be opened as shared, but I don't think you are doing that).
Post more code if you get a chance.