Delete multiple files - vb.net

I'm trying to delete multiple files in same folder with vb.net, but I haven't succeed yet. Help please?
I tried
Dim FileToDelete1 As String
Dim FileToDelete2 As String
Dim FileToDelete3 As String
Dim FileToDelete4 As String
Dim FileToDelete5 As String
FileToDelete1 = Application.StartupPath & "\1.exe"
FileToDelete2 = Application.StartupPath & "\2.dll"
FileToDelete3 = Application.StartupPath & "\3.dll"
FileToDelete4 = Application.StartupPath & "\4.dll"
FileToDelete5 = Application.StartupPath & "\5.dll"
If System.IO.File.Exists( FileToDelete1 ) = True Then
My.Computer.FileSystem.DeleteFile( FileToDelete1 )
ElseIf System.IO.File.Exists( FileToDelete2 ) = True Then
My.Computer.FileSystem.DeleteFile( FileToDelete2 )
ElseIf System.IO.File.Exists( FileToDelete3 ) = True Then
My.Computer.FileSystem.DeleteFile( FileToDelete3 )
ElseIf System.IO.File.Exists( FileToDelete4 ) = True Then
My.Computer.FileSystem.DeleteFile( FileToDelete4 )
ElseIf System.IO.File.Exists( FileToDelete5 ) = True Then
My.Computer.FileSystem.DeleteFile( FileToDelete5 )
End If

Several problems here.
First, File.Exists returns a Boolean value.
The "=True" is unnecessary because you're basically asking if True=True. Fortunately, it is.
Second, file existence or not it's not the only way to fail. For instance, if the file is in use, you'll get an exception. You should handle it.
Third, what if you need to delete a thousand files? Would you create a String for each one of them? There are better options, for instance, the GetFiles method which will return a ReadOnly List of Strings, each one representing one file.
I don't know your needs, but to catch the files you mention, the following call can be made:
FileIO.FileSystem.GetFiles(Application.StartupPath, FileIO.SearchOption.SearchTopLevelOnly, {"?.exe", "?.dll"})
It will get every EXE and DLL file if it's name consists in only one character.
Finally, notice that if the first condition is met, no other will be evaluated, hence no other file will be deleted.
With that implementation you'll need to run the program 5 times in order to delete every file.
GetFiles method solves this as well.
Additionally, consider importing namespaces so you don't need to prefix them in every method call.

Looks like you want to do some thing like this
Dim fileNames() as string={"1","2","3"}
Dim fileTypes() as string={"exe","dll"}
directory.SetCurrentDirectory(Application.StartupPath)
For each fileName as string in fileNames
For each fileType as string in fileTypes
if My.Computer.FileSystem .FileExists (fileName &"."& fileType) then
try
My.Computer.FileSystem.DeleteFile( fileName &"."& fileType )
catch ex As Exception
'**** processings related with exception.
end try
endif
'Dim files() As String = Directory.GetFiles(dirPath, fileName &"." & fileType, SearchOption.AllDirectories)
'For Each FileToDelete as string in files
' My.Computer.FileSystem.DeleteFile( FileToDelete )
'Next
Next
Next

Related

Why System.IO.File.Exists doesn't take if else statement

I have if condition issues when running the following code for an image file:
Dim mainFolder As String = "\\Users\No_Image_Available.png"
Dim saveDirectory As String = "\\IMAGE\"
Dim Filename As String = System.IO.Path.GetFileName(mainFolder)
Dim mainSavePath As String = System.IO.Path.Combine(saveDirectory, Filename)
If System.IO.File.Exists(mainSavePath) Then
'do nothing
Else
'file doesn't exist
My.Computer.FileSystem.CopyFile("\\Users\No_Image_Available.png", "\\IMAGES\No_Image_Available.png")
End If
If the file doesn't exist then it will accept the if statements by either IF Not exist or IF exist... however, if the file already exist it will take the copy argument whether it is in the right if condition or not.
Why is that? It is as if it still reads and accepts the first 'do nothing' condition regardless.
FYI- the paths you see are fake
Issue was that they were server directories. I made the corrections that worked.
Dim Filename = "No_Image_Available.png"
Dim savePathcopy As String = Server.MapPath("~/IMAGES/")
Dim pathToCheckCopy As String = savePathcopy + Filename
'Dim mainSavePath As String = System.IO.Path.Combine(saveDirectory, Filename)
If (System.IO.File.Exists(pathToCheckCopy)) Then
' If System.IO.File.Exists(noImg) = True Then
Else
'file doesn't exist
My.Computer.FileSystem.CopyFile("\\..\Dev\web\WebUsers\...\..\Classified_Ads_V2\No_Image_Available.png", "\\...\Dev\web\WebUsers\...\..\...\IMAGES\No_Image_Available.png")
End If

Renaming all files in a folder

I'm wondering if it's possible to rename all the files in a folder with a simple program, using vb.NET
I'm quite green and not sure if this is even possible.
Lets say there is a folder containing the files:
Text_Space_aliens.txt, fishing_and_hunting_racoons.txt and mapple.txt.
Using a few credentials:
Dim outPut as String = "TextFile_"
Dim fileType as String = ".txt"
Dim numberOfFiles = My.Computer.FileSystem.GetFiles(LocationFolder.Text)
Dim filesTotal As Integer = CStr(numberOfFiles.Count)
Will it be possible to rename these, regardless of previous name, example:
TextFile_1.txt, TextFile_2.txt & TextFile_3.txt
in one operation?
I think this should do the trick. Use Directory.GetFiles(..) to look for specific files. Enumerate results with a for..each and move (aka rename) files to new name. You will have to adjust sourcePath and searchPattern to work for you.
Private Sub renameFilesInFolder()
Dim sourcePath As String = "e:\temp\demo"
Dim searchPattern As String = "*.txt"
Dim i As Integer = 0
For Each fileName As String In Directory.GetFiles(sourcePath, searchPattern, SearchOption.AllDirectories)
File.Move(Path.Combine(sourcePath, fileName), Path.Combine(sourcePath, "txtFile_" & i & ".txt"))
i += 1
Next
End Sub
In your title you state something about chronologically, but within your question you never mentioned it again. So I did another example ordering files by creationTime.
Private Sub renameFilesInFolderChronologically()
Dim sourcePath As String = "e:\temp\demo"
Dim searchPattern As String = "*.txt"
Dim curDir As New DirectoryInfo(sourcePath)
Dim i As Integer = 0
For Each fi As FileInfo In curDir.GetFiles(searchPattern).OrderBy(Function(num) num.CreationTime)
File.Move(fi.FullName, Path.Combine(fi.Directory.FullName, "txtFile_" & i & ".txt"))
i += 1
Next
End Sub
I've never done Lambdas in VB.net but tested my code and it worked as intended. If anything goes wrong please let me know.

For some reason my program is not reading the file that I asked to be read

You can see thatt I've opened the file just below, but I've recently discovered that It is reading a file open above, which I have closed.
Dim TestNO As Integer
Dim myLines As New List(Of String)
Dim sb As StringBuilder
FileOpen(10, "F:\Computing\Spelling Bee\testtests.csv", OpenMode.Input)
Dim Item() As String = Split(fullline, ",")
Dim MaxVal As Integer = Integer.MaxValue
Do Until EOF(10)
fullline = LineInput(10)
If Item(7) > MaxVal Then
MaxVal = Item(7)
TestNO = MaxVal
End If
Loop
This is where I open and close my previous file.
Dim flag As Boolean = False
FileOpen(1, "F:\Computing\Spelling Bee\stdnt&staffdtls\stdnt&staffdtls.csv",
OpenMode.Input)
Do Until EOF(1)
fullline = LineInput(1)
Dim item() As String = Split(fullline, ",")
If enteredusername = item(0) And enteredpassword = item(1) Then
Console.WriteLine()
Console.Clear()
Console.WriteLine("Welcome," & item(3) & item(4))
Threading.Thread.Sleep(1000)
Console.Clear()
flag = True
If item(2) = "p" Then
FileClose(1)
pupilmenu()
ElseIf item(2) = "s" Then
FileClose(1)
staffmenu()
ElseIf item(2) = "a" Then
FileClose(1)
adminmenu()
FileOpen, EOF, and LineInput are all old VB6-style methods which are provided primarily for backwards compatibility. It would be far preferable to use the new .NET classes provided in the System.IO namespace. For instance, this same task is easily performed line this:
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls\stdnt&staffdtls.csv")
Dim fields() As String = line.Split(","c)
If (enteredUserName = fields(0)) And (enteredPassword = fields(1)) Then
' ...
End If
Next
Notice that I also used line.Split rather than Split(line), which is also an old VB6-style method. It's better to use the new String.Split method.
The File.ReadAllLines method opens the file, reads the entire contents of the file, closes the file, and then returns all of the data as an array of strings, with each item in the array being one line from the file. This is a very simple way to read an entire file. If it is a particularly large file, however, it would be better to use a FileStream object to read one line at a time.
Also, it's worth mentioning that reading a CSV file yourself can be complicated. They aren't always as simple as simply splitting on commas. For instance, the following is an example of a valid CSV line:
Bill, "Red, White, and Blue", Smith
As you can see, that line only contains three fields, but it contains four commas. Also, the quotation marks should not be considered as part of the value in the second field. The easiest way to read a CSV file is to use the TextFieldParser class, which handles all of those eccentricities.

How can I check if filename contains a portion of a string in vb.net

I have a userform in 2008 vb express edition. A part number is created from user input via a concat string. I want to then check if a certain portion of the part number exists in the existing file names in a directory. Below is a more detailed explanation.
This is my code for creating a part number from the user input on the form.
L_PartNo.Text = String.Concat(CB_Type.Text, CB_Face.Text, "(", T_Width.Text, "x", T_Height.Text, ")", mount, T_Qty.Text, weep, serv)
I then have the following code to tell the user if the configuration (part no) they just created exists
L_Found.Visible = True
If File.Exists("Z:\Cut Sheets\TCS Products\BLANK OUT SIGN\" & (L_PartNo.Text) & ".pdf") Then
L_Found.Text = "This configuration exists"
Else
L_Found.Text = "This configuration does NOT exist"
End If
This is where I need help. The part no will look like this BX002(30x30)A1SS I want to compare 002(30x30) (just this part of the file name) to all the files in one directory. I want a yes or no answer to the existance and not a list of all matching files. The code below is everything I've tried, not all at the same time.
Dim b As Boolean
b = L_PartNo.Text.Contains(NewFace)
Dim NewFace As String = String.Concat(CB_Face.Text, "(", T_Width.Text, "x", T_Height.Text, ")")
Dim NewFace = L_PartNo.Text.Substring(2, 10)
If filename.Contains(NewFace) Then
lNewFace.Visible = False
Else
lNewFace.Visible = True
End If
The code below was a translation from the answer in C# but it does not work either
Dim contains As Boolean = Directory.EnumerateFiles(path).Any(Function(f) [String].Equals(f, "myfilethree", StringComparison.OrdinalIgnoreCase))
Here's an example of how you can do it without the fancy LINQ and Lambda which seem to be confusing you:
Public Function FileMatches(folderPath As String, filePattern As String, phrase As String) As Boolean
For Each fileName As String In Directory.GetFiles(folderPath, filePattern)
If fileName.Contains(phrase) Then
Return True
End If
Next
Return False
End Function
Or, if you need it to be case insensitive:
Public Function FileMatches(folderPath As String, filePattern As String, phrase As String) As Boolean
For Each fileName As String In Directory.GetFiles(folderPath, filePattern)
If fileName.ToLower().Contains(phrase.ToLower()) Then
Return True
End If
Next
Return False
End Function
You would call the method like this:
lNewFace.Visible = FileMatches(path, "*.pdf", NewFace)
Try this:
lNewFace.Visible = IO.Directory.GetFiles(path, "*.pdf").Where(Function(file) file. _
Substring(2, 10) = NewFace).FirstOrDefault Is Nothing
Consider that the substring function will throw an exception if its arguments exceed the length of the string it is parsing

Overwrite a specific line in a text file using VB.NET

I need to do the following:
Change the line in a text file
[Path] = "c:\this\certain\path\"
with this line
[Path] = "c:\that\other\newer\path\"
These paths will most certainly be different lengths, so I need to either replace what's in the quotes or erase the line completely and enter a new one, but in the same spot, not appended to the end of the document.
This will do the trick
Dim thefile As String = "filepath"
Dim lines() As String = System.IO.File.ReadAllLines("filepath")
lines(number of line you want to replace) = "write what you want to replace here"
System.IO.File.WriteAllLines(filepath, lines)
If you really know exactly how the line you want to replace looks and the file you're reading isn't really big, you could try to just use Replace() to add the new line instead of the old one:
Dim reader As New StreamReader("foo.txt")
Dim writer As New StreamWriter("output.txt")
Dim s = reader.ReadToEnd().Replace("[Path]: C:\oldPath\file.txt", "[Path]: C:\newPath")
writer.Write(s)
One quick way is to use readAllLines and WriteAllLines:
Dim ss() As String
ss = File.ReadAllLines([path])
ss(47) = "c:\that\other\newer\path\"
File.WriteAllLines([path], ss)
If you don't know which line to change, you can search through the array ss for it.
Read the text file into a string, iterate over each line and check if it's in the format:
[Path] = "...." (with regular expressions or simply with string.StartsWith("[Path] = "))
In this loop you should be writing out all other lines and when you are on this [Path] line, print out the modified one.
So in code (sorry, it is in C#):
var reader = File.OpenText("foo.txt");
var writer = new StreamWriter("output.txt");
string line;
while ((line=reader.ReadLine()) != null)
{
if (line.StartsWith("[Path]"))
writer.WriteLine("[Path] = \"c:\\that\\other\\newer\\path\\\"");
else
writer.WriteLine(line);
}
of course, close and dispose the StreamReader and StreamWriter.
Here's the deal: due to the way files are stored on disk, you can't write to one line without also updating every line that follows it.
There are number of ways to do this, and the one most appropriate for your situation will depend on things like the size of the file, are you doing this to a lot of files, where in the file you expect to find this, etc.
But most of the time what I like to do is actually create a copy of the old file... So as I seek through the file looking for the line(s) I need to change, I'm also writing what I've read to a new location. When I find the line, I write out the new information. I then keep seeking through the file until I reach the end at which time I close both streams, delete the original, and rename the new one.
First build a function to give the value of line 'n':
Public Function daValorConfig(ByVal numValor As Long, ByVal nomeFicheiroINI As String) As String
Dim reader As StreamReader = New StreamReader(Application.StartupPath & "\" & nomeFicheiroINI & ".ini")
Dim valor As String = ""
daValorConfig = ""
Dim i As Long = 1
Try
While i <= numValor
valor = reader.ReadLine()
i = i + 1
End While
daValorConfig = valor
reader.Close()
Catch ex As Exception
reader.Close()
MessageBox.Show(ex.Message, "Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
Err.Clear()
End Try
End Function
Then build a procedure that writes the new value on the specified line or keep the old one if the line is not the one you specify:
Public Sub guardaValorConfig(ByVal dados As String, ByVal numValor As Long, ByVal nomeFicheiroINI As String)
Dim writer As StreamWriter = New StreamWriter(Application.StartupPath & "\" & nomeFicheiroINI & ".ini")
Dim valor As String = ""
Dim i As Long = 1
Try
While i <= numValor
If i = numValor Then
writer.Write(dados)
Else
writer.Write(daValorConfig(i, nomeFicheiroINI))
End If
i = i + 1
End While
writer.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
Err.Clear()
End Try
End Sub