Textbox uses previous AutoCompleteCustomSource's suggestions when source is changed - vb.net

I've been searching around for a solution to this problem to no avail. I've got a small VB.net program that allows the user to change the autocomplete source file for the textboxes on the form. If there's no autocomplete file selected on load, the program makes you select one.
If a new file is selected when there's already an autocomplete file, then the textboxes will use suggestions from both until the program is restarted, where it'll start only using the newly selected file. Is there any way to prevent this behaviour?
Here's the code for selecting the file:
Dim fd As OpenFileDialog = New OpenFileDialog()
fd.Title = "Select a file..."
fd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
fd.Filter = "Text files (*.txt)|*.txt"
fd.RestoreDirectory = True
If fd.ShowDialog() = DialogResult.OK Then
My.Settings.streamerFileLocation = fd.FileName
Call Form1_Load(Me, e)
stream1Textbox.Text = ""
stream2Textbox.Text = ""
stream3Textbox.Text = ""
stream4Textbox.Text = ""
End If
And the releveannt part of the Form1_Load sub that it calls:
Using reader As New System.IO.StreamReader(My.Settings.streamerFileLocation)
While Not reader.EndOfStream
autocompleteList.Add(reader.ReadLine())
End While
End Using
stream1Textbox.AutoCompleteCustomSource = autocompleteList
stream2Textbox.AutoCompleteCustomSource = autocompleteList
stream3Textbox.AutoCompleteCustomSource = autocompleteList
stream4Textbox.AutoCompleteCustomSource = autocompleteList

A friend helped me figure it out - the program was still hanging on to the old entries between file changes for whatever reason. Added in autocompleteList.Clear() before the While loop:
Using reader As New System.IO.StreamReader(My.Settings.streamerFileLocation)
autocompleteList.Clear() // THIS LINE
While Not reader.EndOfStream
autocompleteList.Add(reader.ReadLine())
End While
End Using
And hey presto, no more old auto-complete suggestions.

Related

What is the proper way to save an existing file to a user's computer using a SaveFileDialog?

I have a vb.net windows app that creates a PDF. After creation, I want to prompt the user where they want to save the file. The default save folder is different than the folder of the created PDF. I get the SaveDialog box to come up with the default folder and file name that I want. If I choose "Save", I get a message saying that the file does not exist and none of the code below the ShowDialog is executed (I'm sure that I'm doing that part wrong as well).
Dim saveFileDialog1 As New SaveFileDialog
saveFileDialog1.InitialDirectory = MyDocsFolder
saveFileDialog1.FileName = "Report.pdf"
saveFileDialog1.Title = "Save Report"
saveFileDialog1.CheckFileExists = True
saveFileDialog1.CheckPathExists = True
saveFileDialog1.DefaultExt = "pdf"
saveFileDialog1.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
saveFileDialog1.ShowDialog()
If saveFileDialog1.ShowDialog = DialogResult.OK Then
If saveFileDialog1.FileName() <> "" Then
Dim newStream As FileStream = File.Open(newFile, FileMode.Open)
Dim pdfStream As New FileStream(saveFileDialog1.FileName, FileMode.Create)
newStream.CopyTo(fs, FileMode.Append)
newStream.Close()
fs.Close()
End If
End If
you can do it like this:
Imports Microsoft.WindowsAPICodePack.Dialogs
Public NotInheritable Class Form1
Private Sub ButtonSave_Click(sender As Object, e As EventArgs) Handles ButtonSave.Click
Dim Path As String
Using SFD1 As New CommonSaveFileDialog
SFD1.Title = "Where should the file be saved?"
SFD1.Filters.Add(New CommonFileDialogFilter("PDF", ".pdf"))
SFD1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
If SFD1.ShowDialog() = CommonFileDialogResult.Ok Then
Path = SFD1.FileName
Else
Return
End If
End Using
Dim dest As IO.FileInfo
Using fs As IO.FileStream = IO.File.Create(Path & ".pdf")
dest = My.Computer.FileSystem.GetFileInfo(fs.Name)
End Using
End Sub
End Class
Please note that I am using a FileDialog that I downloaded from Visual Studios' own Nuget Package Manager. See image. You don't have to do that, but I prefer this FileDialog because it offers more options than the one that is already included.
So the user enters the file name; thus the path results. In my code example, this creates a blank PDF. It cannot be opened like this yet.
So that something is written in the PDF, you can download itext7 (also via NuGet).
Then, you write Imports iText.Kernel.Pdf,
Imports iText.Kernel.Utils and in your sub Dim pdfwriter As New PdfWriter(dest) with ‘dest’ from above.
I am so blind and stupid...
saveFileDialog1.CheckFileExists = True
Sorry for wasting anyone's time.

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

Why does File.Open() not open the file?

I am implementing a Save File button in my VB.NET Windows Forms application.
I am attempting to encapsulate the normally expected behaviour of Save buttons in Windows applications. I.E: If a file was already selected then open the current file it, write to it and save it; else if there is no current file, or Save As was used, then show a SaveFileDialog, then open, write and save just the same.
I currently have coded the function below but I keep getting an exception:
Cannot access a closed file
The file is created just fine, but is empty (It should contain "Test string"). I can't understand how the file is closed unless some kind of garbage collection is doing away with it somehow??
The current code:
Function SaveFile(ByVal Type As ProfileType, ByVal suggestedFileName As String, ByVal saveAs As Boolean, ByVal writeData As String) As Boolean
Dim FileStream As Stream = Nothing
Dim FolderPath As String = Nothing
Dim CancelSave As Boolean = False
Dim SaveFileDialog As SaveFileDialog = New SaveFileDialog()
Try
If Type = ProfileType.Product Then 'Select the initial directory path
FolderPath = ProductPath
Else
FolderPath = ProfilePath
End If
If (FileName = String.Empty Or saveAs = True) Then 'If a file is not already selected launch a dialog to allow the user to select one
With SaveFileDialog
.Title = "Save"
.AddExtension = True
.CheckPathExists = True
.CreatePrompt = False
.DefaultExt = "xml"
.Filter = "Xml Files (*.xml)|*.xml"
.FilterIndex = 0
.FileName = suggestedFileName
.InitialDirectory = FolderPath
If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
FullyQualfiedPathName = New String(SaveFileDialog.FileName) 'Save the path and name of the file
FileName = Path.GetFileName(FullyQualfiedPathName)
Else
CancelSave = True
End If
.Dispose()
End With
End If
If (FileName <> String.Empty) Then 'Write the string to the file if the filewas correctly selected
FileStream = File.Open(FullyQualfiedPathName, FileMode.OpenOrCreate, FileAccess.ReadWrite) 'Open the file
Using FileStreamWriter As New StreamWriter(FileStream) 'Create the stream writer
FileStreamWriter.Write(writeData) 'Write the data
FileStream.Close() 'Clse the file
End Using
ElseIf (CancelSave <> True) Then 'Only throw an exception if the user *didn't* cancel the SavefileDialog
Throw New Exception("File stream was nothing", New IOException())
End If
Catch ex As Exception
MessageBox.Show(ex.Message & Environment.NewLine & FullyQualfiedPathName)
End Try
Return True
End Function
One problem I see is that you should be putting your File.Open in a Using block:
Using fs = File.Open(fullyQualfiedPathName, FileMode.OpenOrCreate, FileAccess.ReadWrite)
Using writer As New StreamWriter(fs) 'Create the stream writer
writer.Write(writeData) 'Write the data
'fs.Close() <--- you do not need this line becuase the "Using" block will take care of this for you.
End Using
End Using
I'm not sure if this will resolve your issue because I can't run your code, but the Using block will automatically take care of closing and cleaning up disposable instances like FileStream and StreamWriter, even if an exception is thrown.
By the way, you should use proper naming conventions (lower camel case) for local variables.

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

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.

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