Delete a single .txt file if exist in Visual Basic? - vb.net

i have been trying to figure out how to delete a .txt file that constantly change name exept the first 4 ex: THISTEXT-123-45.txt where THISTEXT stays the same but -123-45 changes.
I have found a way to detect it, but i don't know how to delete it.
Dim paths() As String = IO.Directory.GetFiles("C:\", "THISTEXT*.txt")
If paths.Length > 0 Then
Anyone knows the command line to delete that special .txt file?
I am using Visual Basic on visual studio 2013 framework 3.5.

Use the Delete method of System.IO.
Assuming you have write access to C:\
Dim FileDelete As String
FileDelete = "C:\testDelete.txt"
If System.IO.File.Exists( FileDelete ) = True Then
System.IO.File.Delete( FileDelete )
MsgBox("File Deleted")
End If
Deleting a file is quite simple - but dangerous! So be very careful when you're trying out this code.
Edit
To delete all file use *(asterisk) followed with the file extension
example C:\*.txt"
For multiple files
Dim FileDelete As String
FileDelete = "C:\"
For Each FileDelete As String In IO.Directory.GetFiles(FileDelete & "THISTEXT*.txt")
File.Delete(FileDelete)
Next

If you read the MSDN page on GetFiles, you will realize that you have the file name and path in your paths array. You can then iterate through the array deleting your matches.
Dim x as Integer
Dim paths() as String = IO.Directory.GetFiles("C:\", "THISTEXT*.txt")
If paths.Length > 0 Then
For x = 0 to paths.Length -1
IO.File.Delete(paths(x))
Next
End If

To build on the feedback you provided to Omar's answer, it appears that your file path and file name are separate.
You cannot provide them separated by a comma, as commas denote separate parameters passed to a subroutine or function.
To fix this, you need to concatenate them, for example:
Dim fileName As String = "foo.txt"
Dim filePath As String = "C:\"
Dim FileToDelete As String = fileName + filePath
To delete a single .*txt file if it exists:
If (deleteFile("C:\")) Then
MsgBox("File deletion successful")
Else
MsgBox("File couldn't be deleted with the following error: " + exception)
End If
alternatively with concatenation:
If (deleteFile("C:\") Then
MsgBox("File deletion successful")
Else
MsgBox("File couldn't be deleted with the following error: " + exception)
End If
Dim exception As String 'Place this at the beginning of your app's class.
Dim path As String = "C:\"
If (deleteFile(path)) Then
MsgBox("File deletion successful")
Else
MsgBox("File couldn't be deleted with the following error: " + exception)
End If
Private Function deleteFile(ByVal dir) As Boolean
Dim fileToRemove As String
Try
Dim paths() As String = IO.Directory.GetFiles(dir, "THISTEXT*.txt")
For i As Integer = 0 To paths.Length
fileToRemove = paths(i).ToString
System.IO.File.Delete(fileToRemove)
If (Not System.IO.File.Exists(fileToRemove)) Then
Return True
Else
exception = "Unknown error."
Return False
End If
Next
Return False
Catch ex As Exception
exception = ex.Message
Return False
End Try
Return False
End Function
The above function checks if the file exists, if it does it tries to delete it. If the file cannot be deleted, or an error occurs (which is handled), the Function returns False.

Simple example:
For Each path As String In IO.Directory.GetFiles("C:\", "THISTEXT*.txt")
Try
System.IO.File.Delete(path)
Catch ex As Exception
MessageBox.Show(path, "Unable to Delete File")
End Try
Next

Related

vb.net search directory for files containing *.G(num) but NOT *.GP(num)

I'm fairly familiar with bash, but I'm very, ***very**** new to vb.net. I'm searching for an easy way to find files in a folder that end with .G1, .G2, .G3, etc. but NOT .GP1, .GP2, .GP3, etc. Then for each file I need to copy it to another folder using a different file name but the same extension. I've managed to figure this out for the unique files, but there will be an undefined number of these depending on the project and I need to make sure that I get them all. Hard coding is possible, but very, very ugly. Any suggestions?
Here's the remnants of a failed attempt:
Public Sub FindGFiles()
FileList = IO.Directory.GetFiles(searchDir, ".G[1-99]" + , IO.SearchOption.AllDirectories)
For Each foundfile As String In FileList
If foundfile.Contains(".G#") Then
'copy file somehow and retain file extension
Else
MsgBox("No match")
End If
Next
End Sub
The GetFiles-method does only support * and ? wildcard characters.
So you have to get all files with a *.G*-extension first.
In the For Each-loop one can then use the Like-operator to check the desired pattern:
Public Sub CopyGFiles(searchDir As String, destDir As String)
Dim fileList As String() = IO.Directory.GetFiles(searchDir, "*.G*", IO.SearchOption.AllDirectories)
Dim fileName As String
Dim extension As String
For Each foundfile As String In fileList
fileName = IO.Path.GetFileNameWithoutExtension(foundfile)
extension = IO.Path.GetExtension(foundfile)
If extension Like ".G#" OrElse
extension Like ".G##" Then
'copy file to destination, append "_new" to the filename and retain file extension
IO.File.Copy(foundfile, IO.Path.Combine(destDir, fileName & "_new" & extension))
Else
'pattern not matched
End If
Next
End Sub
The method-call would then be as follows:
CopyGFiles("C:\Temp", "C:\Temp\Dest")
This should be done inside a Try/Catch as different exceptions can occur when working with files.
Try
CopyGFiles("C:\Temp", "C:\Temp\Dest")
Catch ex As Exception
MessageBox.Show("An error occured" + vbCrLf + ex.Message)
End Try

Writing Part/Block of File to another File

Please Help: I would like to read one block from file inPath and write to another file outPath.
I am using ReadLines method to read the File line by line and when reach at START_BLOCK, start writing to the output file and continue until you find the END_BLOCK.
I know couple of other methods by copying the whole file into a variable and pick the block what I need. I can't use saving on a variable as my files are very big GB+
The coding I have below copies the line at the "START_BLOCK" Can't really figure it out how to continue writing until the "END_BLOCK". Please suggest and thank you very much in advance.
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If line.Contains("START_BLOCK") Then
sw.WriteLine(line)
'-------HOW DO I CONTINUE TO WRITE UNTIL "END_BLOCK"
End If
Next line
End Using
You could just set a flag to indicate that you are inside of the block, and use that to write out the lines until you find the end tag, e.g. something like this (untested code!):
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Dim insideBlock As Boolean = False
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If line.Contains("START_BLOCK") Then
sw.WriteLine(line)
insideBlock = True
ElseIf line.Contains("END_BLOCK") Then
sw.WriteLine(line)
insideBlock = False
Exit For
ElseIf insideBlock Then
sw.WriteLine(line)
End If
Next line
End Using
UPDATE
Since the comments are getting out of control - here's a version to handle multiple blocks with different start tags but the same end tag (untested since I'm at home on my Mac):
Dim inPath As String = "C:\temprm\myFile.txt"
Dim outPath As String = "C:\temprm\myFileNew1.txt"
Dim insideBlock As Boolean = False
Using sw As StreamWriter = File.CreateText(outPath)
For Each line As String In File.ReadLines(inPath)
If IsStartOfBlock(line) Then
sw.WriteLine(line)
insideBlock = True
ElseIf line.Contains("END_BLOCK") Then
sw.WriteLine(line)
insideBlock = False
ElseIf insideBlock Then
sw.WriteLine(line)
End If
Next line
End Using
'...
' Logic to determine if the line is the start of a block, for example:
Private Function IsStartOfBlock(line As String) As Boolean
Dim startMarkers() As String = {
"START_BLOCK", "START_BLOCK2", "START_BLOCKX"
}
Return startMarkers.Any(Function(x) line.Contains(x))
End Function
The loop will exit at the end of file anyway, so the last block should be ok too.

How to check if sub-folder text file exists

I am trying to search if a text file in a sub-folder exists.
This is the code I am using:
'Checks the program's root folder to see if the root folder exists.
Dim FolderName = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Cake Orders\" & TextBox1.Text))
Dim McKnwoll As String = Path.Combine(FolderName.FullName, Trim(TextBox2.Text) & (" ") & Trim(TextBox3.Text) + ".RTO")
If Not McKnwoll.Exists Then
‘Message to user that file does not exist in sub-folder
Else
‘Message to user that file does exists in sub-folder
End If
I am getting an error that 'Exists' is not a member of 'String'. How can I re-work my code to check if the text file whose name is in the format of "TextBox2.Text & (" ") & TextBox3.Text + ".RTO"; exists.
I am using Visual Basic 2010 Express. Thank you.
File.Exists returns a Boolean indicating whether a file at a certain path exists:
If File.Exists(pathToFile) Then
...
End If
Be sure to include Imports System.IO at the top of your source code file.
You seem quite new in programming. Welcome.
That error message you got ('Exists' is not a member of 'String') tells you exactely what is wrong: You try to ask a string (some text) whether it exists, but what you like to do is to ask a file whether it exists.
The class that provides information about a file is called "FileInfo", and FileInfo has an "Exists" property that you can call:
Dim myFileInfo As New FileInfo(McKnwoll)
If myFileInfo.Exists Then
'do something
End If
That's the object oriented answer, Heinzi's more service oriented one but works, of course, too.
There have been several other small issues I noticed with your code, e.g.
"Cake Orders\" & TextBox1.Text
does not use Path.Combine but makes a string concatenation using fix a "\" as directory separater. Or that the DirectoryInfo is not really used here, the string to the folder is enough.
You also try to handle 3 different issues (reading the values from the user interface, constructing the fullname of the file, checking whether the file exists) in one single code block. I would split them into 3 different ones (actually 4, I would add another one for displaying error messages).
Your simple few lines of codes could be complicated like this ;-)
Imports System.IO
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ReadFileIfPossible(TextBox1.Text, TextBox2.Text, TextBox3.Text)
End Sub
Private Sub ReadFileIfPossible(subfolder As String, part1 As String, part2 As String)
'Get the path to the RTO file
Dim myFilePath As String = Nothing
Try
myFilePath = GetRtoFilePath(subfolder, part1, part2)
Catch ex As Exception
DisplayErrorMessage("Error constructing file name! Please check the values of TextBox1, TextBox2 and TextBox3.")
Return
End Try
'Get the file info
Dim myFile As FileInfo = Nothing
Try
myFile = New FileInfo(myFilePath)
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Check whether it exists
Dim myExists As Boolean = False
Try
myExists = myFile.Exists 'it's IO, everything might throw an exception...
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Display message if not found
If (Not myExists) Then
DisplayErrorMessage("File ""{0}"" could not be found!", myFilePath)
Return
End If
'Read the file
Dim myLines As String() = Nothing
Try
myLines = File.ReadAllLines(myFile.FullName, New UTF8Encoding(True))
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Do something with it...
End Sub
Private Shared Function GetRtoFilePath(subfolder As String, part1 As String, part2 As String) As String
'Check args
If (subfolder Is Nothing) Then Throw New ArgumentNullException("subfolder")
If (part1 Is Nothing) Then Throw New ArgumentNullException("part1")
If (part2 Is Nothing) Then Throw New ArgumentNullException("part2")
'Normalize args
part1 = part1.Trim()
part2 = part2.Trim()
'Build path
Dim myDesktopPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim myFolderPath As String = Path.Combine(myDesktopPath, "Cake Orders")
myFolderPath = Path.Combine(myFolderPath, subfolder)
Dim myFileName As String = String.Format("{0} {1}.RTO", part1, part2)
Dim myResult As String = Path.Combine(myFolderPath, myFileName)
myResult = Path.GetFullPath(myResult)
'Return result
Return myResult
End Function
Private Sub DisplayErrorMessage(message As String, ParamArray args As Object())
Dim myMsg As String = String.Format(message, CType(args, Object()))
MsgBox(myMsg, MsgBoxStyle.OkOnly, "Error")
End Sub
End Class
Have fun.

ByPassing System Files Permissions VB.Net

I started making a file manager which scans a folder selected by user through folderbrowserdialog in vb.net, extract the extentions of every file in every directory or subdirectory using GetFiles() Method with SearchOption.AllDirectories. I am having an UnauthorizedAccessException when it scans the Recycle Bin Folder in logical drive whereas i have seen Softwares like WinRar or R-Studio Scanning and showing every directory without having an exception or error. Following is my code:
Public Sub WriteExtentionsToFile()
Try
Title_Window.FolderBrowserDialog.ShowDialog()
Dim Path As String = Title_Window.FolderBrowserDialog.SelectedPath
'Getting FilesNames
Dim FileNames As String() = GetFilesNames(Path)
Title_Window.LblStatusBar.Text = "File Names Saved"
Dim MaximumForProgressBar As Integer = FileNames.Length
Title_Window.ToolStripProgressBar1.Maximum = MaximumForProgressBar
Title_Window.ToolStripProgressBar1.Step = 1
'Getting Extentions
Dim ExtentionsList As New List(Of String)
For Each item In FileNames
ExtentionsList.Add(System.IO.Path.GetExtension(item))
Next
'Deleting Duplicate Extentions
Dim NoDuplicateExtentionList As New List(Of String)
Dim ExtentionReadFromFile As String() = ReadExtentionsFromFile()'Another Function in my Class Which Reads previously saved extentions in a file and store them in an array
For Each item In ExtentionReadFromFile
NoDuplicateExtentionList.Add(item)
Next
For Each E In ExtentionsList
Dim LastIndexOfDot As Integer = E.LastIndexOf(".")
E = E.Remove(0, LastIndexOfDot + 1)
If NoDuplicateExtentionList.Contains(E.ToLower) = False Then
NoDuplicateExtentionList.Add(E.ToLower)
My.Computer.FileSystem.WriteAllText("d:\ExtentionsList.txt", E.ToString & vbCrLf, True)
End If
Next
MessageBox.Show("Writing Process Completed", "Success")
Catch ex As UnauthorizedAccessException
Dim Buttons As MessageBoxButtons = MessageBoxButtons.AbortRetryIgnore
Dim result As DialogResult
MessageBox.Show(ex.ToString, "Access Denied", Buttons)
If result = Windows.Forms.DialogResult.Ignore Then
'What should be Done Here????
ElseIf result = Windows.Forms.DialogResult.Abort Then
'What should be Done Here????
Else
'What should be Done Here????
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
What should be the solution for thsi problem? Is this about getting the permissions through FileIoPermission Class or something else??

breaking out of sub after if statement in vb.net

I am trying to write code that opens the saveFileDialog only if the variable 'file' is not empty and generates an error message if 'file' is empty. The following code will pop up a error message box when 'file' is empty but will proceed to open the saveFileDialog anyway.
Public Shared Sub DownloadFile(cloudId As CloudIdentity, directoryPath As String, file As String)
Try
Dim cloudFilesProvider = New CloudFilesProvider(cloudId)
If file = "" Then
cloudFilesProvider.GetObjectSaveToFile("EstherTest", directoryPath, file)
End If
Catch
If file = "" Then
MessageBox.Show("Please select file to view")
End If
End Try
End Sub
Can you please direct me.
I think you have the wrong equality operator in your first if-statement.
In humand words, you are telling the compiler:
If file is equal to "" then do ... (If file = "" Then)
What you are trying to say is: if file is NOT equal to "" (If file <> "" Then).
As a second note: Unless an exception occurs, your second if statement will never be called, because the catch block will never be reached. You should put the second clause in a else or else if clause.
I've removed the try catch block for simplicity (and because I'm not really good at the vb.net syntax).
All in all your code should look like this:
Public Shared Sub DownloadFile(cloudId As CloudIdentity, directoryPath As String, file As String)
Dim cloudFilesProvider = New CloudFilesProvider(cloudId)
' if file is not emtpy, proceed
If file <> "" Then
cloudFilesProvider.GetObjectSaveToFile("EstherTest", directoryPath, file)
' else if file is empty, show message box
else if file = "" Then
MessageBox.Show("Please select file to view")
End If
End Sub