How can i open more than 1000 files using openfiledialog? Or is there any method i can use? - vb.net

I am writing a small program in which user will select set of file (mostly .CSV) files and my program will search through them and find required data.
It's working for up to 300 files, but after that its not working. It's giving me an error:
InvalidOperationExceprion was Unhandaled
Too Many files are selected. Select Fewer files and try again.
What should i do?

Like Eric Walker said, open file dialog works with 1,000's and 1,000's of files, there is no reason why it would stop at 300.
The best way to loop though files/folders to get info is to use the .GetFiles() method
Dim OFD As New FolderBrowserDialog
If OFD.ShowDialog = DialogResult.OK Then
For Each f In Directory.GetFiles(OFD.SelectedPath)
If Path.GetExtension(f) = ".txt" Path.GetExtension(f) = ".csv" Then
Dim reader As String() = File.ReadAllLines(f)
For each line as String in reader
DoSomethingAwesome(line)
Next
End If
Next
End If
This will cycle through every file in a certain Directory.
Now if you would like to cycle through every file in a file dialog, then you would use this.
Dim OFD As New OpenFileDialog()
OFD.Multiselect = True
If OFD.ShowDialog = DialogResult.OK Then
For Each f In OFD.FileNames
If Path.GetExtension(f) = ".txt" Path.GetExtension(f) = ".csv" Then
Dim reader As String() = File.ReadAllLines(f)
For Each line As String In reader
DoSomethingAwesome(line)
Next
End If
Next
End If
Give one of these a try depending on your preference.
As a side note, for future posts - please post your attempted code or more details on what you are trying to accomplish and where you are having trouble. Frankly, Im surprised you weren't downvoted (very surprised, people on SO can be ruthless). Just a friendly tip.

Related

Reading multiple textfiles.txt and copying all duplicate lines to a new textfile.txt in VB .net

FIRST PROBLEM:
I am looking for an easiest way to read multiple text files at one time and extract all the duplicate lines from each text file and copy those duplicate lines to a new text file with headings representing name of parent text file. I am dealing with more than 20 text files at a time and it is a mess to go through each one by one. Secondly, I am dealing with large / heavy file (more or less 30,000 lines in each file) .. I am currently using a program with "Stream Reader" and "Stream Writer" and I prefer to have the same approach for my understanding. OR any new and easy way is Welcome !!
SECOND PROBLEM:
I want to compare 2 text files and get the duplicate lines on to a new text file. I don't want to remove/delete/overwrite: Just to copy them across to a new text file.
Please use openfiledialog and savefiledialog for the files.
Thanks a lot in advance.
Best Regards
VB_Learner
Dim Dim optxtfile As New OpenFileDialog
optxtfile.RestoreDirectory = True
optxtfile.Multiselect = False
optxtfile.Filter = "txt files (*.txt)|*.txt"
optxtfile.FilterIndex = 1
optxtfile.ShowDialog()
If (Not optxtfile.FileName = Nothing) Then
Dim lines As New List(Of String)
Using sr As New System.IO.StreamReader(optxtfile.FileName)
While sr.Peek <> -1
Dim line As String = sr.ReadLine()
Dim isNew As Boolean = True
For Each dupl As String In lines
If (dupl = line) Then isNew = False
Next
If (isNew) Then lines.Add(sr.ReadLine())
End While
End Using
Dim svDir As String
If (My.Computer.FileSystem.FileExists(optxtfile.FileName)) Then
My.Computer.FileSystem.DeleteFile(optxtfile.FileName)
svDir = optxtfile.filename
Dim svtxtfile As New SaveFileDialog
svtxtfile.RestoreDirectory = True
svtxtfile.Filter = "txt files (*.txt)|*.txt"
svtxtfile.FilterIndex = 1
svtxtfile.ShowDialog()
If (svtxtfile.FileName = Nothing) Then
svDir = optxtfile.FileName
Else
svDir = svtxtfile.FileName
End If
End If
Using write2text As New System.IO.StreamWriter(svDir)
For Each line As String In lines
write2text.WriteLine(line)
Next
End Using
End If
End Sub

Unhandled exception has occured in the application vb.net

Ok, so my code look like the following.
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("E:/Med/Dra.txt", False)
file.WriteLine(NameBasic)
file.WriteLine(LastBasic)
file.WriteLine(PhoneBasic)
file.Close();
All those are variables that I have set for text boxes. This is OnbuttonClick(...
Now for my onload I take the info out of the notepad, Here is the code,
Dim read As System.IO.StreamReader
read = My.Computer.FileSystem.OpenTextFileReader("E:/Med/Dra.txt")
lblNameBasic.Text = read.ReadLine
lblLastBasic.Text = read.ReadLine
lblPhoneBasic.Text = read.ReadLine
read.Close();
I have placed the notepad(txt file) inside a flashdrive folder named med
I got the saving info to work and load, so I took the flashdrive to another computer, I got this nasty error, talking about the System.IO and all this other stuff.
It then prompts me, would you like to continue with errors, or quit.
I click continue than all the saved data does not load. Am I doing something wrong here??
Also sorry for alot of questions today. (The .exe is in the flashdrive, med folder aswell).
First of all, your path is incorrect - E:/Med/Dra.txt should be E:\Med\Dra.txt. And here how you use open file dialog - this is just basis, you need to take care of error handling, etc.
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "txt files (*.txt)|*.txt"
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim read As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(openFileDialog1.FileName)
End If
I think, main reason why you had errors is because incorrect path. You can also check if path exists
If Not File.Exists("E:\Med\Dra.txt") Then
MessageBox.Show("There is no such file")
Exit Sub
End If
' Code to open non existing file will be skipped

get full path using openfiledialog

Simple utility to get a file for use.
Using openfiledialog I am trying to get the full path EG: File = text1.txt and it is located in c:\temp. So the full path is C:\temp\text1.txt.
But all I can get is the file name. I've searched I've hunted, I'e tried for a couple of hours and nothing works.
Here is code with comments...
'open the openfile dialog so the user can search for a file
Dim openFileDialog1 As New OpenFileDialog()
'set the root to the z drive
openFileDialog1.InitialDirectory = "Z:\"
'make sure the root goes back to where the user started
openFileDialog1.RestoreDirectory = True
'show the dialog
openFileDialog1.ShowDialog()
'check there is something to work with... the user did not exit before selecting a file etc.
If openFileDialog1.FileName.Length = 0 Then
'if the user selected a file set the value of the replacefile text box
Else
TB_ReplacementFile.Text = System.IO.Path.GetFullPath(openFileDialog1.FileName)
End If
All I get is the file name...
The MSDN documentation and numerous posts all over the place say all you need is openfiledialog.FileName. However this did not work for me, can't tell you why. What DID work is to use this:
TB_ReplacementFile.Text = System.IO.Path.GetFullPath(openFileDialog1.FileName)
This works great, I get what I need. I cannot explain why I have to do this. Not sure how I can be the problem, but that must be the problem right?!
Hopefully this helps someone.
The FileName Property returns the full path.
The file name includes both the file path and the extension. If no files are selected, this method returns an empty string ("").
If (openFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK) Then
TB_ReplacementFile.Text = openFileDialog1.FileName
End If
Not 100% sure if this would resolve the issue you're having, or if it's simply just another way to handle it, but I prefer to check the DialogResult. I.E:
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "Z:\"
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.Ok Then
Console.WriteLine(openFileDialog1.fileName)
End If
this worked to get the directory or path
dim sDir as String = System.IO.Path.GetDirectoryName(openfiledialog1.FileName.ToString)

Merging 2 or more text files after edit in VB.net

Helo there!
it seems that i am facing a problem with my code in VB.net. Please be patient as i am a complete beginner in programming. I am trying to code a program that will load 2 or more txt files, find and exclude specific lines (starting with some characters or contain some characters) and then merge and save only one file that will contain all the information after the editing (from all the files).
I am using openfiledialog and i have set the multiselect to true. Below is the code for the OpenfileDialog:
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
For Each File In OpenFileDialog1.FileNames
My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName)
Next
If i am correct, it loads the filenames and reads all the text from the files. For the editing i am using the following code:
Dim outputLines As New List(Of String)()
For Each line As String In System.IO.File.ReadLines(OpenFileDialog1.FileName)
Uline1 = line.StartsWith("text1")
Uline2 = line.StartsWith("text2")
Uline3 = line.StartsWith("text3")
Uline4 = line.StartsWith("text4")
Uline5 = line.StartsWith("text5")
Uline6 = line.StartsWith("text7")
Uline7 = line.StartsWith("sometext")
Trash = line.Contains("^")
If Uline1 Or Uline2 Or Uline3 Or Uline4 Or Uline5 Or Uline6 Or Uline7 Or Trash Then
outputLines.Remove(line)
Else
outputLines.Add(line)
End If
Next
For the output i am using a savefiledialog with the following code:
SaveFileDialog1.DefaultExt = "txt"
SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
SaveFileDialog1.RestoreDirectory = True
If (SaveFileDialog1.ShowDialog() = DialogResult.OK) Then
System.IO.File.WriteAllLines(SaveFileDialog1.FileName, outputLines)
Although the files are being loaded correctly, the edit seems to happen only in one file (the last selected) and again the program saves only one file.
Could you please point me to the right direction?
You need to nest your loops through the file names returned by the open file dialog, and the lines returned by the ReadLines calls. You also don't need to remove lines from the outputLines list, since they are never added. Something like:
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim outputLines As New List(Of String)()
For Each fileName In OpenFileDialog1.FileNames
For Each line As String In System.IO.File.ReadLines(fileName)
Uline1 = line.StartsWith("text1")
Uline2 = line.StartsWith("text2")
Uline3 = line.StartsWith("text3")
Uline4 = line.StartsWith("text4")
Uline5 = line.StartsWith("text5")
Uline6 = line.StartsWith("text7")
Uline7 = line.StartsWith("sometext")
Trash = line.Contains("^")
If Not (Uline1 Or Uline2 Or Uline3 Or Uline4 Or Uline5 Or Uline6 Or Uline7 Or Trash) Then
outputLines.Add(line)
End If
Next
Next
End If
If the files are very large you will start to run into memory issues, and will need to write the data out as it is read instead of keeping it all in memory.
UPDATE
Based on the comments, if you want to check the following line to determine if the current line should be written, you could use something like this. Note the use of ReadAllLines and the For loop.
Dim outputLines As New List(Of String)()
For Each fileName In OpenFileDialog1.FileNames
Dim lines() As String = System.IO.File.ReadAllLines(fileName)
For i As Integer = 0 To lines.Count - 1
Dim line As String = lines(i)
If line.StartsWith("19") AndAlso i < lines.Count - 2 AndAlso lines(i + 1).StartsWith("15") Then
outputLines.Add(line)
outputLines.Add(lines(i + 1))
i += 1
End If
Next
Next

Opening a notepad from a button in VB.net

I want to create a button in VB.net that lets me browse my hard drive for the specified notepad file i want to open and retrieve the contents from it, i only have tried using FileStream and StreamReader but this wont let me manually select the notepad file instead i have to declare a default filename. Any sample codes would be appreciated thanks in advance, i just need a starting point. I am really stuck to this.
This the code i am using right now, but i have to specify the correct file name on it:
Dim fStream As New System.IO.FileStream("messages.txt", IO.FileMode.Open)
Dim sReader As New System.IO.StreamReader(fStream)
Dim Index As Integer = 0
Do While sReader.Peek >= 0
ReDim Preserve sArray(Index)
sArray(Index) = sReader.ReadLine
Index += 1
Loop
If I understand your question correctly, you want to have an option to choose which textfile to open, if so you can try this:
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
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 your loop here
End If
Catch Ex As Exception
MessageBox.Show(Ex.Message)
Finally
If (stream IsNot Nothing) Then
stream.Close()
End If
End Try
End If
I think you may be using the wrong approach with a FileStream. Instead look to allow a user to select a file, then use Process.Start to open Notepad.
Take a look here for examples on selecting a file. The page here then details Process.Start.
I'm happy to provide more code samples directly here, but those two pages should be sufficient.