breaking out of sub after if statement in vb.net - 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

Related

Trying to write files on multiple lines

i am trying to have variables linked to together like this: (login,pass,name) i want to have several line of those but whenever i register it clears the file help would be appreciated thanks.
Private Sub btn_register_Click(sender As Object, e As EventArgs) Handles btn_register.Click
Dim newline As String
Dim anything As String
password = txt_passwordregister.Text
username = txt_usernameregister.Text
If password <> "" And username <> "" Then
If validatepass() = False Then
MsgBox("please enter more than 8 characters")
Else
newline = txt_usernameregister.Text & "," & txt_passwordregister.Text
If rad_student.Checked Then
anything = newline & "," & txt_fullname.Text
Student.WriteLine(anything)
Student.Close()
Else
End If
MsgBox("You are now registered!")
End If
End If
End Sub
You might want to specify what kind of file you are talking to.
but since you don't actually indicate something in particular, here i used StreamWriter to append lines of text to a file.
Using studentWriter As StreamWriter = New StreamWriter("(<path>\<filename>.<txt>)", True)
studentWriter.WriteLine(anything)
End Using
sorry for my bad english.
You didnt show what's happening with the object Student before..
We assume you are using StreamWriter here??
Our best guess is that you open the file in new file mode rather than append mode..
To enable Append mode, provide the parameter when you create the Student object like this :
Dim Student as New StreamWriter("[File Location]",[Append Mode])
When [Append Mode] is True it will append the file and write after the last line you've written into it before.
When [Append Mode] is False it will treat the file as a new file and all the content inside will be lost.

Illegal Characters in path when grabbing text from a file?

I'm getting illegal characters in path, but the directory (the path) will be different for everyone, so I'm not setting a value for the "path", it's what the user chooses in the file explorer.
I haven't seen a solution for VB.net yet so here's the code I have now:
myFileDlog.InitialDirectory = "c:\"
myFileDlog.Filter = "Txt Files (*.txt)|*.txt"
myFileDlog.FilterIndex = 2
myFileDlog.RestoreDirectory = True
If myFileDlog.ShowDialog() =
DialogResult.OK Then
If Dir(myFileDlog.FileName) <> "" Then
Else
MsgBox("File Not Found",
MsgBoxStyle.Critical)
End If
End If
'Adds the file directory to the text box
TextBox1.Text = myFileDlog.FileName
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(myFileDlog.FileName)
Dim lines() As String = IO.File.ReadAllLines(fileReader)
At Dim lines() As String = IO.File.ReadAllLines(fileReader)
It breaks with the Illegal Characters in Path exception, and I'm not sure how to test where the illegal character is, because it's grabbing from your own file directory. Any help with this?
The problem originated from this line:
Dim fileReader As String = My.Computer.FileSystem.ReadAllText(myFileDlog.FileName)
fileReader takes all string contents from the corresponding file name and pass it into File.ReadAllLines method at next line, throwing ArgumentException with illegal file path message if illegal characters found inline.
Correct way to read file contents using ReadAllLines is using predefined file path or directly using FileDialog.FileName property as argument given below:
Using myFileDlog As OpenFileDialog = New OpenFileDialog()
' set dialog filters here
If (myFileDlog.ShowDialog() = DialogResult.OK) Then
If Dir(myFileDlog.FileName) <> "" Then
Dim lines() As String = File.ReadAllLines(myFileDlog.FileName)
For Each line As String In lines
' do something with file contents
Next
Else
' show "file not found" message box
End If
End If
End Using
Since ReadAllLines already being used to fetch all file contents, usage of ReadAllText may be unnecessary there.

Check if file exist before counting the length of the string in text file

I am having a hard time figuring up why this code of mine gives me an unhandled exception error where in fact it is an if statement..
If (Not System.IO.File.Exists("C:\file.txt") And System.IO.File.ReadAllText("C:\file.txt").Length <> "20") Then
MessageBox.Show("Code executed!")
Else
MessageBox.Show("Failed to execute!")
End If
Can you please tell me what have I missed?
It is better to break down code as shown below which makes detecting and debugging a whole lot easier. Better to write a few extra lines so what happen here does not happen at all.
Dim fileName As String = "C:\file.txt"
Dim FileText As String = ""
If IO.File.Exists(fileName) Then
FileText = IO.File.ReadAllText(fileName)
If FileText.Length <> 20 Then
MessageBox.Show("Code executed!")
Else
' recover
End If
Else
MessageBox.Show("Failed to execute!")
End If

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

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

FileExist not working vb.net

I really can not understand why the exception is triggered.
I created this code that performs some checks for the correctness of the license.
The function isittrial occurs if the trial software is creating a hidden file, this file is then checked with File.exist.
The problem is the following:
the file is created by isittrial but for some strange reason you enable the exception of file.exist, what can I do to fix it?
I really can not understand why it does not work.
isittrial() 'this function make the file to check
Dim percorsoCompleto As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
Try
If My.Computer.FileSystem.FileExists(directory) Then
Dim fileReader As String
Dim dire As String = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Software\cc.txt"
fileReader = My.Computer.FileSystem.ReadAllText(directory,
System.Text.Encoding.UTF32)
Dim check = DeCryptIt(fileReader, "aspanet")
Dim datadecripted As String = DeCryptIt(Registry.GetValue("HKEY_CURRENT_USER\Software\cc", "end", ""), "aspanet")
If Date.Now < check And check <> datadecripted Then
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
Else
End If
Else
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
DeActivate()
ForceActivation()
End If
Catch ex As Exception
MsgBox("License not valid", MsgBoxStyle.Critical, "Attention!")
'DeActivate()
'ForceActivation()
End Try
This line
If My.Computer.FileSystem.FileExists(directory) Then
seems to test for the existence of a file passing the name of a directory (or an empty string or whatever, we can see how this variable is initialized). In every case the result will be false.
Then your code jumps to an else block with the same error message of the exception fooling your perception of the error.
Try instead
Dim percorsoCompleto As String = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
percorsoCompleto = Path.Combine(percorsoCompleto, "Software", "cc.txt")
Try
If My.Computer.FileSystem.FileExists(percorsoCompleto) Then
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(percorsoCompleto,
System.Text.Encoding.UTF32)
.....
Notice that I have removed the path concatenation with a more fail safe call to Path.Combine