Change .SaveFile to save as keeping the file format - vb.net

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

Related

Open Explorer and redirect to specific path after SaveFileDialog

I create a simple function to download a file from the URL and then save it to some folder using SaveFileDialog and then the program will open Windows Explorer to the path of the saved file.
but I don't know how to get the last path of the SaveFileDialog
here is my code :
Dim path = "myURL"
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.FileName = dgvAttachmentName & dgvFileExtensi
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Using client As New WebClient()
client.DownloadFile(path, saveFileDialog1.FileName)
Process.Start("explorer.exe", "/root," & saveFileDialog1.FileName)
End Using
End If
If I use SaveFileDialog1.FileName, I get the full path of the File but with a FileName, but I also can't use replace to remove the file name from the path because User can change the file name every time they want to save a file.
How to get the path only from the SaveFileDialog then open explorer to that path ?
Try this:
Dim fi As New System.IO.FileInfo(saveFileDialog1.FileName)
Dim Path = fi.DirectoryName
all together:
Dim path = "myURL"
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.FileName = dgvAttachmentName & dgvFileExtensi
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Using client As New WebClient()
client.DownloadFile(path, saveFileDialog1.FileName)
Dim fi As New System.IO.FileInfo(saveFileDialog1.FileName)
Dim Path = fi.DirectoryName
Process.Start("explorer.exe", "/root," & Path )
End Using
End If

How to include the message box within the Open file dialog in VB.net

In my previous question: How to know if the file I'm opening is a .txt file or not in VB.net
I ask here how to know if I'm opening .txt file or not.
The code below is my code for opening a .txt file and prompt the user if the file is .txt of not.
Dim filename As String = String.Empty
Dim TextLine As String = ""
Dim SplitLine() As String
Dim ofd1 As New OpenFileDialog()
ofd1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
ofd1.FilterIndex = 2
ofd1.RestoreDirectory = True
ofd1.Title = "Open Text File"
'get the filename of the txt file
If ofd1.ShowDialog() = DialogResult.OK Then
'if the file is not .txt file
If (Path.GetExtension(filename).ToLower() <> ".txt") Then
MessageBox.Show("Please select text Files only", _
"RMI", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
'show the open file dialog
ofd1.ShowDialog()
'if the file is .txt file
Else
filename = ofd1.FileName
End If
'if the filename is existing
If System.IO.File.Exists(filename) = True Then
Dim objReader As New System.IO.StreamReader(filename)
'read the text file and populate the datagridview
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
TextLine = TextLine.Replace(" ", "")
SplitLine = Split(TextLine, ",")
dvList.Rows.Add(SplitLine)
Loop
End If
If the file that I selected is not .txt file, here is the output:
If I open a file that is not existing, here is the output:
In the 1st image, it only show the error message box, but in the 2nd image, the error message box is within the open file dialog.
My question is how can I show the error message box of the 1st image with the open file dialog?
Thank you.
Notes:
No need to check the extension after you show the form, but you should instead set the appropriate filter in order to limit the selection of .txt files only "txt files (*.txt)|*.txt"
You can use the OpenFileDialiog.CheckFileExists and OpenFileDialiog.CheckPathExists properties to prevent user to enter an invalid file name/path (display an error message)
Not sure you need to check a second time if the file exists if you use CheckFileExists / CheckPathExists
You should always dispose a form that you show using ShowDialog() method.
You should dispose the StreamReader
Dim filename As String = String.Empty
Dim TextLine As String = ""
Dim SplitLine() As String
Using ofd1 As New OpenFileDialog()
ofd1.Filter = "txt files (*.txt)|*.txt"
ofd1.FilterIndex = 2
ofd1.CheckPathExists = True
ofd1.CheckPathExists = True
ofd1.RestoreDirectory = True
ofd1.Title = "Open Text File"
'get the filename of the txt file
If ofd1.ShowDialog() = DialogResult.OK Then
filename = ofd1.FileName
Using objReader As New System.IO.StreamReader(filename)
'read the text file and populate the datagridview
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
TextLine = TextLine.Replace(" ", "")
SplitLine = Split(TextLine, ",")
dvList.Rows.Add(SplitLine)
Loop
End Using
End If
End Using
Here i add the label which is hidden. (name: pathlabel)
button (open file)
add openfiledialog from toolbox
this is so simple.
Open File button:
openfiledialog.showdialog()
OpenFileDialog_FileOk :
PathLabel.Text = System.IO.Path.GetExtension(OpenFileDialog.FileName)
If PathLabel.Text = ".txt" Then
Dim Objectreader As New System.IO.StreamReader(OpenFileDialog.FileName)
TextBox1.Text = Objectreader.ReadToEnd
Objectreader.Close()
Else
MsgBox("please select only Text Document (.txt)", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Error")
End If
Thank you...
Instead of this you must set the filter to openfiledialog
button code (open file)
Openfiledialog.showdialog()
openfiledialog.filter = "Text Document|*.txt"

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

Visual Basic, Opening a file, what is wrong with my code?

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).