How do I get the file name only, assign it to a variable and use later? - vb.net

I have the following code:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
Dim saveFileName As String = ""
saveFileDialog1.Filter = "txt files (*.txt)|*.txt"
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
myStream = saveFileDialog1.OpenFile()
saveFileDialog1.FileName = saveFileName
Using sw As StreamWriter = New StreamWriter(myStream)
' Add some text to the file.
sw.WriteLine(DateTime.Now + " - " + saveFileName) ' Date and File title header
sw.WriteLine("-------------------")
' Arbitrary objects can also be written to the file.
sw.Write("The date is: ")
sw.WriteLine(DateTime.Now)
sw.Close()
End Using
If (myStream IsNot Nothing) Then
' Code to write the stream goes here.
myStream.Close()
End If
End If
End Sub
The variable is saveFileName, however when I use the saveFileDialog1.FileName as it, it is empty or provides the full path to the file, how do I only get the name? (such as test.txt)

Use Path.GetFileName
saveFileName = Path.GetFileName(saveFileDialog1.FileName)

DIM fileName = IO.Path.GetFileName(SavefileDialog.FileName)

Related

vb.net use saveFileDialog with XmlTextWriter

i am new with VB.net
and i manage to write input to xml file using
Dim writer As New XmlTextWriter("xmlInputFile.xml", System.Text.Encoding.UTF8)
now i want user to write they own name and path location of the xml file .
reading couple of example of SaveFileDialog and i come out with this code
Dim path As String = IO.Path.GetFullPath(SaveFileDialog1.FileName)
Dim writer As New XmlTextWriter(ToString(path), System.Text.Encoding.UTF8)
which give an error
thanks
btw the button code below
Private Sub Button3_Click_3(sender As Object, e As EventArgs) Handles btnSave.Click
Dim SaveFileDialog1 As SaveFileDialog = New System.Windows.Forms.SaveFileDialog
SaveFileDialog1.DefaultExt = ".xml"
SaveFileDialog1.Filter = "XML files(.xml)|*.xml|all Files(*.*)|*.*"
SaveFileDialog1.InitialDirectory = "desktop"
If SaveFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
Save_Data()
End If
End Sub

RTF code saved when I save a txt file

I'm working on a VB.NET project.
I have a richtextbox and a button to save what I write.
But when I open the file I see this:
I want to show just the text "ilyasscj isjdivs", not all the RTF code.
This is my code:
Private Sub EnsregistrerSousToolStripMenuItem_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
EnsregistrerSousToolStripMenuItem.Click
SaveFileDialog1.InitialDirectory = "c:\"
SaveFileDialog1.Filter = "Texte|*.txt|RTF|*.rtf|Tous|*.*"
SaveFileDialog1.Title = "enregistrer un fichier"
If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
fich = SaveFileDialog1.FileName
RichTextBox1.SaveFile(fich)
End If
End Sub
Private Sub EnregistrerToolStripMenuItem_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
EnregistrerToolStripMenuItem.Click
If fich = "" Then
SaveFileDialog1.InitialDirectory = "c:\"
SaveFileDialog1.Filter = "Texte|*.txt|RTF|*.rtf|Tous|*.*"
SaveFileDialog1.Title = "enregistrer un fichier"
If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
fich = SaveFileDialog1.FileName
Try
RichTextBox1.SaveFile(fich)
Catch ex As Exception
' MsgBox(ex.Message)
End Try
End If
Else
Try
RichTextBox1.SaveFile(fich)
Catch ex2 As Exception
MsgBox(ex2.Message)
End Try
End If
End Sub
I will appreciate any help.
The RichTextBox.SaveFile(String) pre-defined behaviour is described in the documentation:
Saves the contents of the RichTextBox to a rich text format (RTF)
file.
If you define more format options in the SaveFileDialog, you also need to verify what format the User chose and instruct the SaveFile method to use that format when streaming the output to disk.
As an example, use a Select Case switch to select the RichTextBoxStreamType corresponding to the User choice (see the documentation for the meaning of other possible fomat options):
Dim sfd As SaveFileDialog = New SaveFileDialog()
sfd.Filter = "Texte (*.txt)|*.txt|RTF (*.rtf)|*.rtf|Tous (*.*)|*.*"
sfd.Title = "Enregistrer un fichier"
sfd.DefaultExt = "txt"
If sfd.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim Filter As Integer = sfd.FilterIndex
Dim FileFormat As RichTextBoxStreamType
Select Case Filter
Case 1
FileFormat = RichTextBoxStreamType.PlainText
Case 2
FileFormat = RichTextBoxStreamType.RichText
Case Else
FileFormat = RichTextBoxStreamType.UnicodePlainText
End Select
Dim FileName As String = sfd.FileName
RichTextBox1.SaveFile(FileName, FileFormat)
End If

Changing the Name of a File Selected in FileDialog

I am trying to make an application which takes a file from your computer, renames that file with variables from 4 different combo boxes and then uploads it to an FTP server.
I have gotten everything working except the renaming part....
what i am trying to do is this.
slectedFile.pdf would become combobox1_combobox2_combobox3_combobox4.pdf
The file path is stored in a variable named FileName i know how to update FileName with the combobox values, but does it keep the original Path?
How would i go about doing this?
This is the code i have so far.
IP_box, User_Box and Pass_box are the textboxes for the appropriate server information.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(IP_Box.Text.ToString), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential(User_Box.Text.ToString, Pass_Box.Text.ToString)
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte
Try
System.IO.File.ReadAllBytes(FileName)
Catch ex As Exception
MessageBox.Show(ex.Message)
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Filename = System.IO.Path.GetFullPath(FD.FileName)
End If
End Function
Thank you in advance
At the end of your subroutine, you try to retrieve the file; you incorrectly use System.IO.Path.GetFullPath(FD.FileName) as FD.FileName already provides the full file name.
In order to rename the file to your desired name, you need to firstly evaluate the values of each ComboBox, of which can be done as a loop:
Private Function enumerateCheckboxes(ByVal path As String)
Dim fName As String
For Each Control In Me.Controls
If (TypeOf Control Is CheckBox AndAlso DirectCast(Control, CheckBox).Checked) Then
fName += CStr(Control.Name) + "_"
End If
Next
fName = path + fName.Substring(0, fName.Length - 1) + ".pdf"
Return fName
End Function
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Dim Filename As String = FD.FileName
Filename = StrReverse(Filename)
Filename = Mid(Filename, InStr(Filename, "\"), Len(Filename))
Filename = StrReverse(Filename)
Return Filename
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
OpenDialog()
End Sub
If I test with a file from the desktop:
However now we might possibly have an issue that the file does not exist, thus the program will crash. To fix this, we can quickly rename the file for the upload, and rename it back when it's finished.
The complete code:
Imports System.IO
Public Class Form1
Dim Filename As String
Dim originalFile As String
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Filename = FD.FileName
Filename = StrReverse(Filename)
Filename = Mid(Filename, InStr(Filename, "\"), Len(Filename))
Filename = StrReverse(Filename)
Return Filename
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(IP_Box.Text.ToString), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential(User_Box.Text.ToString, Pass_Box.Text.ToString)
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte
Try
Filename = OpenDialog()
System.IO.File.ReadAllBytes(Filename)
Catch ex As Exception
MessageBox.Show(ex.Message)
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
FileSystem.Rename(originalFile, Filename)
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End Sub
Private Function enumerateCheckboxes(ByVal path As String)
originalFile = path
Dim fName As String
For Each Control In Me.Controls
If (TypeOf Control Is CheckBox AndAlso DirectCast(Control, CheckBox).Checked) Then
fName += CStr(Control.Name) + "_"
End If
Next
fName = path + fName.Substring(0, fName.Length - 1) + ".pdf"
Return fName
End Function
End Class

How to add else statement into downloading code?

I'm making a file downloader and I want it to download files to either my selected directoy or default directory.
Downloading code is here:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Button1.Enabled = False
Button1.Text = "Updating..."
WebBrowser1.Visible = True
Dim uri As System.Uri = New System.Uri("http://199.91.154.170/e9f6poiwfocg/pei02c8727sa720/Ultra+v08.zip")
Dim webclient As System.Net.WebClient = New System.Net.WebClient()
Dim path As String =
If apppath = Nothing then
New String(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "test\\Test.zip"))
Else New String
(apppath)
End if
Dim fileInfo As System.IO.FileInfo = New System.IO.FileInfo(path)
If Not System.IO.Directory.Exists(fileInfo.Directory.FullName) Then
System.IO.Directory.CreateDirectory(fileInfo.Directory.FullName)
End If
AddHandler webclient.DownloadFileCompleted, AddressOf webclient_DownloadDataCompleted
webclient.DownloadFileAsync(uri, path)
End Sub
Private Sub
And user selected path apppath is defined here:
If apppath = "" Then
Dim dialog As New FolderBrowserDialog()
dialog.RootFolder = Environment.SpecialFolder.Desktop
dialog.SelectedPath = Path.Combine(Environment.GetFolderPath( _
Environment.SpecialFolder.ApplicationData))
dialog.Description = "Select directory where to install the files"
If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
apppath = dialog.SelectedPath
End If
My.Computer.FileSystem.WriteAllText(apppath & " apppath.txt", apppath, False)
End If
How to fix Dim path As String else statement?
Thanks in advance!
If I am understanding your question correctly then I believe there is a simple solution, which is this:
Dim path As String
If apppath = Nothing then
path = New String(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "test\Test.zip"))
Else New String
path = apppath
End if
If I have not understood your requirements correctly, then please provide more information.

Trying to open a docx file from a bytestream - file corruption error

we consistently get a file corrupted error message when opening a docx file from a saved bytestream, evry other file type works just ok
Below is code from a sample form that replciate the issue
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Objective is to be able to copy a file to a bytestream then create a new document from that stream and then opne it.
'This replicates the behaviour of our primary application where it stores and retrieves the stream from a database
'With docx files we consistently experience some sort of corruption in the write of the original file
'When selecting .doc or other format files we do not encounter the same problem
'use selected file
Dim _o1 As String = TextBox1.Text
'get its bytestream
Dim fs As New FileStream(_o1, FileMode.Open, FileAccess.Read)
Dim byteStream(Convert.ToInt32(fs.Length)) As Byte
fs.Read(byteStream, 0, Convert.ToInt32(fs.Length))
'create a new file and use the bytestream to create it and save to disk
Dim _o As String = "C:\" & Now.Ticks & getNewFileName()
Dim fs1 As New FileStream(_o, FileMode.OpenOrCreate, FileAccess.Write)
Using bw As New BinaryWriter(fs1)
bw.Write(byteStream)
bw.Flush()
End Using
'open the new document
System.Diagnostics.Process.Start(_o)
Application.DoEvents()
End Sub
Private Function getNewFileName() As String
Dim fi As New FileInfo(TextBox1.Text)
Return Now.Ticks.ToString & fi.Name
End Function
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.InitialDirectory = "c:\"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
OpenFileDialog1.Filter = "docx files |*.docx"
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
TextBox1.Text = OpenFileDialog1.FileName
End If
End Sub
Forgive me, but that is some messed up code.
Dim _o As String = "C:\" & Now.Ticks & getNewFileName()
will become...
Dim _o As String = "C:\" & Now.Ticks & Now.Ticks.ToString & fi.Name
Example result "C:\" "634015010433498951" "634015010433498951" "FileName.txt" is probably not what you are expecting unless you intend to subtract the two tick counts to determine how long it took to populate FileInfo.
Your FileStream corruption could be a encoding issue, off by one file length issue, or even a long filename in a deep path could a problem. Instead of using FileStream, this code should work fine:
Dim sourceFile As String = TextBox1.text
Dim fi As New System.IO.FileInfo(sourceFile)
Dim destFile = "C:\" & Now.Ticks & fi.Name
fi.CopyTo(destFile)
'open the new document
System.Diagnostics.Process.Start(destFile)