Opening a notepad from a button in VB.net - 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.

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

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

Write File with text from resources visual basic

I'm writing some program in VB, and I want to create txt file with text from file in resources. You didn't understood, did you? So, it goes like this.
Dim path As String = "c:\temp\MyTest.txt"
' Create or overwrite the file.
Dim fs As FileStream = File.Create(path)
' Add text to the file.
Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.")
fs.Write(info, 0, info.Length)
fs.Close()
is code for creating txt file with certain text. But, I need the following.
Dim fd As New FolderBrowserDialog
fd.ShowDialog()
is the only function that I have in program, and, when folder is selected, I need to create file in that folder, file's name should be config.cfg, but, text in file which is going to be created in selected folder should be text from mine txt file which is in Recources.
I've tried
Dim path As String = fd.SelectedPath
Dim fs As FileStream = File.Create(path)
' upisuje tekst u fajl
Dim info As Byte() = New UTF8Encoding(True).GetBytes(application.startuppath & "\..\..\Resources\config.cfg")
fs.Write(info, 0, info.Length)
fs.Close()
but the text I got in file is directory from where is my program debugged.
Any ideas to do this? :)
If you added a text file to your resources, then you can try something like this:
Using fbd As New FolderBrowserDialog
If fbd.ShowDialog(Me) = DialogResult.OK Then
File.WriteAllText(Path.Combine(fbd.SelectedPath, "config.cfg"), My.Resources.config)
End If
End Using
The file I added was called config, and it made a config.txt file in my resource library.