FileExist not working vb.net - 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

Related

PDFsharp Beta 1.50 PdfTextField, Null Exception Error, But Still Works?

I'm using PDFsharp 1.50 beta 3b. I'm mainly using it to access the ability to use newer PDF Documents. I'm not using any newer features. Down converting my PDF docs is killing them and I don't know why. That said;
Private Sub Print_Form()
Dim filename As String = ""
If IO.File.Exists(String.Format("{0}Template\Form.pdf", AppDomain.CurrentDomain.BaseDirectory)) Then
filename = String.Format("{0}Template\Form.pdf", AppDomain.CurrentDomain.BaseDirectory)
Else
MessageBox.Show("You're missing the Templates directory. If you don't know what this means, tell your IT Administrator.", "Missing Files")
Exit Sub
End If
Dim PDFDocument As PdfSharp.Pdf.PdfDocument = PdfSharp.Pdf.IO.PdfReader.Open(filename, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Modify)
Dim form As PdfSharp.Pdf.AcroForms.PdfAcroForm = PDFDocument.AcroForm
If form.Elements.ContainsKey("/NeedAppearances") Then
form.Elements("/NeedAppearances") = New PdfSharp.Pdf.PdfBoolean(True)
Else
form.Elements.Add("/NeedAppearances", New PdfSharp.Pdf.PdfBoolean(True))
End If
Try
'the subsequent line causes the exception to be thrown
CType(form.Fields("StringTest"), PdfSharp.Pdf.AcroForms.PdfTextField).Text = "Test"
Catch ex As Exception
Clipboard.SetText(ex.StackTrace)
End Try
CType(form.Fields("CheckBoxTest"), PdfSharp.Pdf.AcroForms.PdfCheckBoxField).Checked = True
PDFDocument.Save("temp.pdf")
Dim p As New System.Diagnostics.ProcessStartInfo()
p.Verb = "print"
p.WindowStyle = ProcessWindowStyle.Hidden
p.FileName = "temp.pdf"
p.UseShellExecute = True
System.Diagnostics.Process.Start(p)
End Sub
This creates an error;
An unhandled exception of type 'System.NullReferenceException' occurred in PdfSharp.dll
Additional information: Object reference not set to an instance of an object.
at PdfSharp.Pdf.AcroForms.PdfTextField.RenderAppearance()
at PdfSharp.Pdf.AcroForms.PdfTextField.set_Text(String value)
at WOTC_FE.frmInterview.Print_ICF() in d:\Programming\FE\FE\Applications\frmInterview.vb:line 2886
Now what makes this weird and why I'm asking is that this still works with the try/catch block. It will fill the field and the file has the correct text in the PDF file. I just want to know why does it throw this exception?
I figured out the issue. The new PDFSharp uses a different access method for it's controls.
First, our declarations;
Dim PDFDocument As PdfSharp.Pdf.PdfDocument = PdfSharp.Pdf.IO.PdfReader.Open(filename, PdfSharp.Pdf.IO.PdfDocumentOpenMode.Modify)
Dim form As PdfSharp.Pdf.AcroForms.PdfAcroForm = PDFDocument.AcroForm
For checkboxes;
CType(form.Fields(<Field Name>), PdfSharp.Pdf.AcroForms.PdfCheckBoxField).Checked = True
And for strings;
PDFDocument.AcroForm.Fields("Field Name").Value = New PdfSharp.Pdf.PdfString("Input Text")
Doing it this way works, doesn't need a try/catch block, and doesn't throw an error.

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

File.Copy not working - no error

Please take a look at this code. For some reason that I can't figure out, the File.Delete() line isn't getting fired and I'm not getting an error.
' hard-coded for testing
Dim path As String = "C:\Program Files (x86)\Test\Program\Program.exe"
Dim appDir As String = My.Application.Info.DirectoryPath
Dim iniPath As String = appDir & "\config.ini"
Dim outputPath As String = appDir & "\output.ini"
Dim textLine As String = ""
Dim reader = File.OpenText(iniPath)
Dim writer = New StreamWriter(outputPath)
' Read the lines in the ini file until the pathToExecutable line is found and write the path to that line
While (InlineAssignHelper(textLine, reader.ReadLine())) IsNot Nothing
If textLine.StartsWith("pathToExecutable=") Then
writer.WriteLine("pathToExecutable=" & path)
Else
writer.WriteLine(textLine)
End If
End While
reader.Dispose()
reader.Close()
writer.Dispose()
writer.Close()
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Return path
You stated that you are not getting an error, but if you don't implement exception handling, you're most probably getting errors and throwing them away (pun intended).
Use a try/catch around any of your System.IO.File operations, and even more, you can implement specific handles and catch specific exceptions.
Try
File.Copy(outputPath, iniPath, True)
File.Delete(outputPath) ' THIS ISN'T GETTING FIRED
Catch ioException As IOException
'The specified file is in use.
MessageBox.Show(ioException.Message)
Catch ex As Exception
'Some other error apart for file in use.
MessageBox.Show(ex.Message)
End Try
Ericosg's suggestion about using a try/catch lead me to the issue: I had the file open in a streamreader earlier in my code, but never closed it there.

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