Create save file dialog with encoding combobox choices like Notepad - vb.net

I'm trying to create a savefiledialog to save the text found in a richtextbox
but with different choices for encoding like notepad:
the problem for me is that combobox which allow for different encoding
how could i add it to the savefiledialog, this is my code:
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
My.Computer.FileSystem.WriteAllText(SaveFileDialog1.FileName, RichTextBox1.Text, False)
End If

You want to specify the Filter property of the SaveFileDialog:
Using sfd As SaveFileDialog = New SaveFileDialog()
With sfd
.Filter = "Text|*.txt|Word|*.docx|Etc|*.etc"
If (sfd.ShowDialog = DialogResult.Ok Then
'...
End If
End With
End Using

Related

How to WriteAllText but restrict to overwrite the existing file?

Jan 8. 2023:
The AppendAllText can append into existing file and can create a file if no file exist.
the WriteAllText can Write into new created file and overwrite the existing file.
I'm trying to find another alltext for what I want to happen.
What I want to do is to save my textboxcontent.text into txt file.
I want to save 3 different content that will be displayed into my textboxcontent.text
And I only have one button.
That one button will open savefiledialog but with the code I have, I can only do 2 things, Write and Append.
Now, This is what suppose to happen.
*If I save the textcontent.text to an existing txt file, it will prompt message box "Do you want to overwrite this file?" And even if I click Yes, it will not allow to.
I must be able to create new txt file since I was not able to overwrite the file.
The reason is because I don't want to delete or overwrite the existing file with important information saved in it.
I hope somebody can help me.
This is the code I have.
```Imports System.io
Private lastSaveFileName As String = String.Empty
Private Function GetSaveFileName3(ByVal suggestedName As String) As String
Using sfd3 As New SaveFileDialog()
sfd3.Filter = "Text Files (*.txt) |*.txt"
sfd3.FileName = suggestedName
sfd3.OverwritePrompt = True
If DialogResult.OK Then
End If
If sfd3.ShowDialog() = DialogResult.OK Then
MessageBox.Show(
Me, "Your activity is not saved! This file have records from your last session, you cannot overwrite this file. Please create new file to save new records.",
"Save error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
)
Else
End If
Return String.Empty
End Using
End Function
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
lastSaveFileName = GetSaveFileName3(lastSaveFileName)
If Not String.IsNullOrEmpty(lastSaveFileName) Then
File.AppendAllText(lastSaveFileName, TextContent.Text)
End If
End Sub ' This code above includes IMPORTS.IO
Jan 9, 2023: Update
This is what I've done so far.
I tried to use the File.Exist but I don't know where to place it to make it run in the way I wanted.
Please see this code and help me fix it.
This code is running well in almost the way I want. I'm missing something.
Imports System.IO
Private lastSaveFileName As String = String.Empty
Private Sub SaveFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveFile.Click
If Not File.Exists(lastSaveFileName) Then
lastSaveFileName = GetSaveFileName(lastSaveFileName)
If Not String.IsNullOrEmpty(lastSaveFileName) Then
File.WriteAllText(lastSaveFileName, txtdisplay1.Text)
End If
ElseIf File.Exists(lastSaveFileName) Then
lastSaveFileName = GetSaveFileName2(lastSaveFileName)
If Not String.IsNullOrEmpty(lastSaveFileName) Then
File.WriteAllText(lastSaveFileName, txtdisplay1.Text)
End If
End If
End Sub
Private Function GetSaveFileName2(ByVal suggestedName As String) As String
Using sfd As New SaveFileDialog()
sfd.Filter = "Text Files (*.txt) |*.txt"
sfd.FileName = suggestedName
sfd.OverwritePrompt = True
If sfd.ShowDialog() = DialogResult.OK Then
'If File.Exists(lastSaveFileName) Then
MessageBox.Show(
Me, "Your activity is not saved! This file have records from your last session, you cannot overwrite this file. Please create new file to save new records.",
"Save error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
)
End If
Return String.Empty
End Using
End Function
Private Function GetSaveFileName(ByVal suggestedName As String) As String
Using sfd As New SaveFileDialog()
sfd.Filter = "Text Files (*.txt) |*.txt"
sfd.FileName = suggestedName
sfd.OverwritePrompt = True
If sfd.ShowDialog() = DialogResult.OK Then
Return sfd.FileName
End If
Return String.Empty
End Using
End Function
With this code, I was able to save the textdisplay to a txtfile but it's like, it's bypassing the Elseif function.
Sometimes, poeple forgot to avoid important files and accidentally deleted it. This is what I'm preventing to happen.
I let the overwriteprompt true to let it ask the user if they want to replace. It accidentally click the yes, this will show message "This file have records from your last session, Please create new file to save new records." means that even the user want to replace it, the program will not allow it. I don't want to remove that scenario.
(Scenario 1)
What happen in this code is this, when I click the button, savefiledialog pop up and giving me choice how I want to save the textdisplay.
I can create new file or replace existing file.
First, I choose to replace, and a messagebox shows and saying, I can't replace the file.
Then I create new file, it lets me save the txt display normally.
(scenario 2)
That's what I want. The code runs that way at first, but if you click the button again, and try to create new file first, the message box will show saying I can't replace the file. then when I choose to replace, no message box shows and the file was replace. I lost the file.
That's where I need help. I only want the Scenario 1.
Please try on your own I you don't get what I mean.
I tried this and this code works the way I want.
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
If File.Exists(saveFileDialog1.FileName) Then
MessageBox.Show("A file with that name already exists. Please select a different file name or choose a different location to save the file.")
Else
File.WriteAllText(saveFileDialog1.FileName, Txtdisplay1.Text)
End If
End If
End Sub
Answered by: schoemr

Saving listbox's file not just its name

Im working on my first injector in VB.NET.
Im trying to save the loaded dll in listbox, but it only saves the name.
I select the dll, inject, it saves my.settings, but once I reopen the injector it only saves the dll's name, not its path, so I have to browse and select it again
I was thinking about maybe I have to save openfiledialog or something but really got no clue
Inject button:
My.Settings.dll = New Specialized.StringCollection
My.Settings.dll.AddRange(dll.Items.Cast(Of String).ToArray)
My.Settings.Save()
My.Settings.process = SteamTextBox2.Text
My.Settings.Save()
On form load:
If My.Settings.dll IsNot Nothing Then dll.Items.AddRange(My.Settings.dll.Cast(Of String).ToArray)
The problem with this the injector only needs the dll's name without path
Dim ExeName As String = IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath)
Private Sub Inject()
pszLibFileRemote = OpenFileDialog1.FileName
End Sub
OpenFileDialog1.Filter = "DLL (*.dll) |*.dll"
OpenFileDialog1.ShowDialog()
OpenFileDialog1.ToString()
If IO.File.Exists(OpenFileDialog1.FileName) Then
Dim TargetProcess As Process() = Diagnostics.Process.GetProcessesByName(SteamTextBox2.Text)
If TargetProcess.Length = 0 Then
...
Else
Call Inject()
I want it to load the actual selected file not just it's name
Nothing is functionally wrong with your code. I guess the problem is with how you load the paths into the listbox in the first place. Here is some code to do that.
Add a new button called LoadButton, then this code for the handler
Private Sub LoadButton_Click(sender As Object, e As EventArgs) Handles LoadButton.Click
Dim filenames As IEnumerable(Of String)
Using dialog As New OpenFileDialog
dialog.Filter = "Application extensions (*.dll)|*.dll|All files (*.*)|*.*"
dialog.Multiselect = True
Select Case dialog.ShowDialog()
Case DialogResult.OK
filenames = dialog.FileNames
Case Else
filenames = Nothing
End Select
End Using
filenames = filenames.Select(Function(fn) System.IO.Path.GetFileName(fn))
If filenames?.Any() Then dll.Items.AddRange(filenames.ToArray())
End Sub
This will put the full path into the listbox. Does this solve the problem?

VB.NET 2010 Passing Picture from OpenFile Dialog Box to another form

I am creating a loan program that opens a Custom Form Dialog Box, you choose the picture, click open and then need to pass it to another form to use after hitting OK from the Dialog Box. This is my code when I click the Logo File button from my custom Dialog Form.
The Form is called Dialog Form and I need to send the picture to the NewLoanCaculatorForm to populate a picture area in the form.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogoFile.Click
Dim mystream As Stream = Nothing
'Open the File to pickup icon for Loan Calculator
Dim OpenFileDialog1 As New OpenFileDialog
'Set up and display the open File Dialog
With OpenFileDialog1
'Begin in the current Directory
.InitialDirectory = "C:\"
.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
End With
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
mystream = OpenFileDialog1.OpenFile()
If (mystream IsNot Nothing) Then
' I believe the coded goes here but I'm stuck
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (mystream IsNot Nothing) Then
mystream.Close()
End If
End Try
End If
End Sub
This is how I usually do things like this:
Create global variable in the DialogForm:
Public Property sPath as String
or
Public Property imgLogo as Image
To get the Image do this:
imgLogo = Image.FromFile(OpenFileDialog1.FileName)
Or simply do:
sPath = OpenFileDialog1.FileName
instead of
mystream = OpenFileDialog1.OpenFile()
Then when you have done this you close the form by clicking the OK button or whatever you call it.
Then in your main form NewLoanCaculatorForm where you call DialogForm you simply do:
img = DialogForm.imgLogo
or
path = DialogForm.sPath
img = Image.FromFile(path)
Depending on which way you stored the info in the DialogForm.
Also, if you are looking for images I would recommend you not to have .txt in your filter. That would seriously ruin the execution.

Printing an RTF file using Printdialog in VB.NET

I have this code:
Private printDocument1 As New PrintDocument()
Private stringToPrint As String
Private Sub ReadFile()
Dim docName As String = "print_doc.rtf"
Dim docPath As String = fsPathPrintDoc
printDocument1.DocumentName = docName
Dim stream As New FileStream(docPath + docName, FileMode.Open)
Try
Dim reader As New StreamReader(stream)
Try
stringToPrint = reader.ReadToEnd()
Finally
reader.Dispose()
End Try
Finally
stream.Dispose()
End Try
End Sub
and I do the printing using:
ReadFile()
printDocument1.Print()
I want to print a rtf file using a VB.NET printdialog.show(), because in want to choose specific printers for printing, but my above code i dont have any idea, how i can embed printdialog here.
This is required because i want to print that file using printers available on different systems using network. Now all these available printers are available for me in print dialog, what i want is to simply print a particular file in my drive using printdialog()
Also, I tried to find a possibility to print a file using printdialog and printdocument but unfortunately failed.
Edit:
I found http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.aspx but it does not includes printdialog
You assign your PrintDocument to the PrintDialogs Document Property, it will then add the selected printer to your Document. You then print the Document as normal.
PrintDialog1.AllowSomePages = True
PrintDialog1.ShowHelp = True
PrintDialog1.Document = printDocument1 'Assign your Document here
Dim result As DialogResult = PrintDialog1.ShowDialog()
If (result = DialogResult.OK) Then
printDocument1.Print()
End If

Load from file into listbox?

So in my program i am trying to make it so that when you press a button it opens a "choose file" popup(where the user can choose a text file) then after the user chooses it the program will automatically load each line of the textfile into a listbox.
But i have been researching it and the only thing i have been able to find is a file>open thing. So how cold i make it open a "open" dialogue on the press of a button
and since i haven't been able to find anything on the open dialogue i haven't looked for anything on the loading each line of it into a listbox, so if anyone wants ot help me with that it would be great.
and i do not have any code to show you as the rest of my program has no relevance to this
Using FD As New OpenFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
Listbox1.Items.Clear
ListBox1.Items.AddRange(IO.File.ReadAllLines(FD.FileName))
End If
End Using
EDIT: Answer on the comment:
If you can use LINQ, then its a one row of code to read all lines from the listbox and write it to a file:
Save using SaveFileDialog and LINQ
Using FD As New SaveFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
IO.File.WriteAllLines(fd.filename, (From p As String In ListBox1.Items Select p).ToArray)
End If
End Using
If you can't use LINQ, then you can do this instead:
Save using SaveFileDialog and FOR/EACH
Using FD As New SaveFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim FileContent As String = ""
For Each i As String In ListBox1.Items
FileContent &= i & vbCrLf
Next
IO.File.WriteAllText(FD.FileName, FileContent)
End If
End Using
Basically, there are a couple parts here. First, you want to create an Open File Dialog box that prompts the user for where the file is. Here is how you do that:
http://www.homeandlearn.co.uk/net/nets4p6.html
Next, you want to read the text file in line by line into your listbox. Here is how you read your text file (you will need to modify the code to have it add the lines to the listbox instead of doing a Console.WriteLine:
http://msdn.microsoft.com/en-us/library/db5x7c0d.aspx
OpenFileDialog from MSDN:
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myStream As Stream = Nothing
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
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
' Insert code to read the stream here.
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub
As you can see from the comments, you can read a stream after the user has opened the file. You can then read this stream using, for example, a StreamReader. That will give you the data within the file the user chose. Depending on what you want, you can then parse that data and add it to your listbox.