Visual Basic, Opening a file, what is wrong with my code? - vb.net

The 'reader' within the if statement is showing "Expression is not a method", what am I doing wrong?
Thanks
Dim reader As New CSVReader
OpenFileDialog2.Filter = "CSV File (*.csv)|*.csv"
OpenFileDialog2.RestoreDirectory = True
If OpenFileDialog2.ShowDialog() = DialogResult.OK Then
reader(OpenFileDialog2.FileName)
reader.DisplayResults(DataGridView1)
'Return OpenFileDialog2.FileName
Else
End If
I simply moved the Dim and it worked.
OpenFileDialog2.InitialDirectory = "a:"
OpenFileDialog2.Filter = "CSV File (*.csv)|*.csv"
OpenFileDialog2.RestoreDirectory = True
If OpenFileDialog2.ShowDialog() = DialogResult.OK Then
Dim reader As New CSVReader(OpenFileDialog2.FileName)
reader.DisplayResults(DataGridView1)
'Return OpenFileDialog2.FileName
Else
End If
Thanks

On this line:
reader(OpenFileDialog2.FileName)
You're trying to call a constructor on an object that is already constructed. That's not possible, so the VB compiler is interpreting this as you trying to call the reader object as if it were a function.
Just don't declare the reader until you have the filename, so that you can pass the name to the constructor when you actually construct it, like so
OpenFileDialog2.Filter = "CSV File (*.csv)|*.csv"
OpenFileDialog2.RestoreDirectory = True
If OpenFileDialog2.ShowDialog() = DialogResult.OK Then
Dim reader As New CSVReader(OpenFileDialog2.FileName)
reader.DisplayResults(DataGridView1)
'Return OpenFileDialog2.FileName
Else
End If

You missed out the method name in reader(OpenFileDialog2.FileName).

Related

FTP Client uploads only 0KB files

I am having a small problem with my FTP client.
Choosing a file works, renaming that file with 4 variables works.
It's the upload that is causing me trouble.
Whenever a file is uploaded to the FTP server it says it is 0KB.
I am thinking of 2 possible problems:
Visual studio tells me that the variable file is used before it has been assigned a value, to make sure it isn't null i did the following.
Dim file As Byte()
If (Not file Is Nothing) Then
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End If
This Takes care of any possible Errors.
The second one is fName, same warning as with file, and I took care of it the same way.
another possibility is that my code just takes the 4 variables and makes that into a file and uploads it, hence the 0KB size....
Here's my code:
Dim Filename As String
Dim originalFile As String
Private Function enumerateCheckboxes(ByVal path As String)
originalFile = path
Dim fName As String
For Each Control In Me.Controls
If (TypeOf Control Is ComboBox AndAlso DirectCast(Control, ComboBox).SelectedIndex > -1) Then
fName += CStr(Control.SelectedItem.Key) + "_"
End If
Next
Try
fName = path + fName.Substring(0, fName.Length - 1) + ".jpg"
Catch ex As Exception
MsgBox(ex.Message)
MsgBox("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
Return fName
End Function
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Dim Filename As String = FD.FileName
Filename = StrReverse(Filename)
Filename = Mid(Filename, InStr(Filename, "\"), Len(Filename))
Filename = StrReverse(Filename)
MsgBox(enumerateCheckboxes(Filename))
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ip" & enumerateCheckboxes(Filename)), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("username", "password")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte
Try
Filename = OpenDialog()
If (Not Filename Is Nothing) Then
System.IO.File.ReadAllBytes(Filename)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
If (Not Filename Is Nothing) Then
FileSystem.Rename(originalFile, Filename)
End If
Dim strz As System.IO.Stream = request.GetRequestStream()
If (Not file Is Nothing) Then
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End If
End Sub
End Class
I have looked at multiple threads with the same problem as me.
Threads like this
But i dont believe this applies to my problem.
If you would be so kind to explain what i did wrong and how i can fix and avoid this in the future, my debugging is still a bit rough...
Thank you in advance!
Visual Studio is giving you that warning because you never assign anything to the file array. I think that on the line where you have:
System.IO.File.ReadAllBytes(Filename)
You really meant to have:
file = System.IO.File.ReadAllBytes(Filename)

Change .SaveFile to save as keeping the file format

How can I turn this statement into a "save as" dialog box?
Me.TextBox4.SaveFile(System.Environment.GetFolderPath(Environment.SpecialFolder.MyComputer) + "\MyDocs\Test.xml", RichTextBoxStreamType.UnicodePlainText)
I need to preserve this format since it is the only one that worked properly when file is saved.
Thanks.
You can try something like this. Create a SaveFileDialog and pass it all the parameters for the default locations and file names. Create a new file stream based on your file (creating or overwriting) and passing that stream to the SaveFile method of the RichTextBox
Using sfd As New SaveFileDialog()
sfd.AddExtension = True
sfd.Filter = "*.xml|*.xml"
sfd.OverwritePrompt = True
sfd.DefaultExt = ".xml"
sfd.CreatePrompt = False
sfd.InitialDirectory = Path.Combine(Environment.SpecialFolder.MyComputer, "\MyDocs\")
sfd.FileName = "Test.xml"
If sfd.ShowDialog = Windows.Forms.DialogResult.OK AndAlso sfd.FileName <> String.Empty Then
Using sf As New FileStream(sfd.FileName, FileMode.Create)
TextBox4.SaveFile(sf, RichTextBoxStreamType.UnicodePlainText)
End Using
End If
End Using

Storing a selected notepad its contents to FileStream

I am currently having problems in storing the contents of any selected notepad file from openFileDialog to the FileStream. My code states a default filename as i do not know how to revise the FileStream code, i want it to register the filename of my selected notepad.
By default it would only read the contents of "messages.txt", i want to have a freedom to choose any notepad file and retrieve the data from it. Any kind of help or advice will do thanks in advance.
here is my code:
Dim Stream As New System.IO.FileStream("messages.txt", IO.FileMode.Open)
'i need to do something about this line above
Dim sReader As New System.IO.StreamReader(Stream)
Dim Index As Integer = 0
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "D:\work"
openFileDialog1.Filter = "txt files (*.txt)|*.txt"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
Stream = openFileDialog1.OpenFile()
If (Stream IsNot Nothing) Then
Do While sReader.Peek >= 0
ReDim Preserve eArray(Index)
eArray(Index) = sReader.ReadLine
RichTextBox3.Text = eArray(Index)
Index += 1
Delay(2)
Loop
End If
Catch Ex As Exception
MessageBox.Show(Ex.Message)
Finally
If (Stream IsNot Nothing) Then
Stream.Close()
End If
End Try
End If
End Sub
I rearranged your code just a bit. Basically you were creating a stream, and then creating the reader for the stream to "messages.txt". Later you set the stream object to a new stream based on the OpenFile method of the file open dialog. But your reader was still pointing to the first stream you opened, so that is what was getting read. I've changed the code below to not open that first stream, and to create the reader after you have created the stream based on the file the user selected.
'don't create a stream hear and the reader, because you are just recreating a stream later in the code
Dim Stream As System.IO.FileStream
Dim Index As Integer = 0
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "D:\work"
openFileDialog1.Filter = "txt files (*.txt)|*.txt"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
'This line opens the file the user selected and sets the stream object
Stream = openFileDialog1.OpenFile()
If (Stream IsNot Nothing) Then
'create the reader here and use the stream you got from the file open dialog
Dim sReader As New System.IO.StreamReader(Stream)
Do While sReader.Peek >= 0
ReDim Preserve eArray(Index)
eArray(Index) = sReader.ReadLine
RichTextBox3.Text = eArray(Index)
Index += 1
Delay(2)
Loop
End If
Catch Ex As Exception
MessageBox.Show(Ex.Message)
Finally
If (Stream IsNot Nothing) Then
Stream.Close()
End If
End Try
End If
End Sub

cancel throws error in OpenFileDialog box

I'm trying to implement an OpenFileDialog box, its works fine except if I choose to click cancel then program throws an error, saying that file can't be found, which confuses me cause I didnt select a file.
The following is the code. how I can implement the cancel button?
OpenFileDialog1.InitialDirectory = "C:\"
OpenFileDialog1.FileName = "Select a Batch file..."
OpenFileDialog1.Filter = "Batch files (*.bat) | *.bat"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.Cancel Then
OpenFileDialog1.Dispose()
End If
Dim R As New IO.StreamReader(OpenFileDialog1.FileName)
TextBox4.Text = R.ReadToEnd
R.Close()
Button4.Enabled = True
Button6.Enabled = True
You commented out the (inadequate) handling of cancelling the dialog. Put it back in:
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.Filter = "Batch files (*.bat)|*.bat|All files|*.*"
Dim result = openFileDialog1.ShowDialog()
If result = DialogResult.Cancel Then
Return ' Just leave the method
End If
' … rest of method
You should also think about proper variable names. OpenFileDialog1, TextBox3 and Button2 are never appropriate names. Good identifiers increase the readability of your code tremendously.
Dialog will dispose itself in both cases - you simply don't do anything if user cancels his intended action. This should do it:
OpenFileDialog1.InitialDirectory = "C:\"
OpenFileDialog1.FileName = "Select a Batch file..."
OpenFileDialog1.Filter = "Batch files (*.bat) | *.bat"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim R As New IO.StreamReader(OpenFileDialog1.FileName)
TextBox4.Text = R.ReadToEnd
R.Close()
Button4.Enabled = True
Button6.Enabled = True
End If
Of course you will have to add some additional error handling but that is another story.
Dim result = OpenFileDialog1.ShowDialog()
If result = True Then
Dim R As New IO.StreamReader(OpenFileDialog1.FileName)
TextBox4.Text = R.ReadToEnd
R.Close()
Button4.Enabled = True
Button6.Enabled = True
else
' handle the error, e.g. msgbox (no vaild file chosen"
End If
This is what worked for me for my project.
Dim bResult As DialogResult = sfdReportFile.ShowDialog()
If bResult = DialogResult.OK Then
tbFilePathName.Text = sfdReportFile.FileName.ToString
End If
You will need to define the result as a DialogResult to check if it was OK and send the file path to whatever you needed it for.
On my project, I used the SaveFileDialog. If the user closed the dialog window, then there is no file name, and an error occurs. With my below code, my process wont run unless there is a file name to use.
If SaveFileDialog1.FileName = Nothing Then
Else
Code to run here when a file name is selected.
End If
The same thing can be run for the OpenFileDialog. Just add an if then to check if a filename has been saved, if not, don't run the code.

Problem in reading from text file in my code

Using Microsoft Visual Studio 2008:
' Create an instance of the open file dialog box.
Dim openFileDialog1 As OpenFileDialog = New OpenFileDialog
' Set filter options and filter index.
openFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
openFileDialog1.FilterIndex = 1
openFileDialog1.Multiselect = True
' Call the ShowDialog method to show the dialogbox.
Dim UserClickedOK As Boolean = openFileDialog1.ShowDialog
' Process input if the user clicked OK.
If (UserClickedOK = True) Then
Using sr As StreamReader = New StreamReader() ' <-----
Dim line As String
' Read and display the lines from the file until the end
' of the file is reached.
Do
line = sr.ReadLine()
Console.WriteLine(Line)
Loop Until line Is Nothing
End Using
End If
On the line marked, how can I pass the path of the selected file into the StreamReader constructor? Thanks!
Edit: Amended my sample code as per Hans suggestion.
Just use the FileName property of the OpenFileDialog class as:
If openFileDialog1.ShowDialog() = DialogResult.OK Then
Using sr As StreamReader = New StreamReader(openFileDialog1.FileName)
' do stuff
End Using
End If
Edit: Though I just saw that you've got MultiSelect set to True, so you'd have to use the FileNames property instead and loop through it and open the StreamReader for each file.
So something like:
If openFileDialog1.ShowDialog() = DialogResult.OK Then
For Each file As String In openFileDialog1.FileNames
Using sr As StreamReader = New StreamReader(file)
' do stuff
End Using
Next
End If