Changing the Name of a File Selected in FileDialog - vb.net

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

Related

VB2010 read a csv in datagrid, update in grid and save to same csv

Created a procedure in VB2010 to read a csv-file in datagridviewer, update cells in grid and save to same csvfile
Opening the csvfile in the datagridviewer works fine,
Updating in the datagridviewer works fine also
But when I save the datagrid to a csv-file with the same name, I get an error message "The process Can not access the file because it is used by an other process".
But if I save it to an other filename it is ok.
Then I tried to copy the new file with the new filename back to the original filename.
I received still the same error message that I cant copy because the file is still in use.
Does anybody now how to solve this.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "H:\Data\2014\Software\VB2010\"
OpenFileDialog1.Filter = "CSV files (*.csv)|*.CSV"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
Me.TextBox1.Text = fName
Dim TextLine As String = ""
Dim SplitLine() As String
DataGridView1.ColumnCount = 5
DataGridView1.Columns(0).Name = "Name"
DataGridView1.Columns(1).Name = "Gender"
DataGridView1.Columns(2).Name = "Age"
DataGridView1.Columns(3).Name = "Ranking"
DataGridView1.Columns(4).Name = "Date"
If System.IO.File.Exists(fName) = True Then
Dim objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
Else
MsgBox("File Does Not Exist")
End If
End Sub
Private Sub SaveGridDataInFile(ByRef fName As String)
'method called by button2
Dim I As Integer = 0
Dim j As Integer = 0
Dim cellvalue$
Dim rowLine As String = ""
Try
Dim objWriter As New System.IO.StreamWriter(fName, True)
For j = 0 To (DataGridView1.Rows.Count - 2)
For I = 0 To (DataGridView1.Columns.Count - 1)
If Not TypeOf DataGridView1.CurrentRow.Cells.Item(I).Value Is DBNull Then
cellvalue = DataGridView1.Item(I, j).Value
Else
cellvalue = ""
End If
rowLine = rowLine + cellvalue + ","
Next
objWriter.WriteLine(rowLine)
rowLine = ""
Next
objWriter.Close()
objWriter = Nothing
MsgBox("Text written to file")
Catch e As Exception
MessageBox.Show("Error occured while writing to the file." + e.ToString())
Finally
FileClose(1)
End Try
Call copy_file()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'çall method SaveGridDataInFile
SaveGridDataInFile(Me.TextBox1.Text)
' FileCopy("H:\Data\2014\Software\VB2010\datagr_ex2.csv", "H:\Data\2014\Software\VB2010\datagr_ex.csv")
End Sub
Sub copy_file()
Dim FileToDelete As String
FileToDelete = "H:\Data\2014\Software\VB2010\datagr_ex.csv"
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
MsgBox("File Deleted")
End If
FileCopy("H:\Data\2014\Software\VB2010\datagr_ex2.csv", "H:\Data\2014\Software\VB2010\datagr_ex.csv")
End Sub
My guess is you need to close the StreamReader you use to load the file before you can reopen the file to save it. The StreamReader class implements IDisposable so you can use VB.Net's Using Statement to automatically close the file when you're finished reading, i.e.
If System.IO.File.Exists(fName) = True Then
Using objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
End Using
Else
MsgBox("File Does Not Exist")
End If

prompt for opening a save dialog for excel file using vb.net

Iam using visual studio 2012,
i would like to open "save dialog" to choose where to save my file instead of using fixed path,
the following code is a sample of what i would like to use it in:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xlsWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlsWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim xls As New Microsoft.Office.Interop.Excel.Application
Dim resourcesFolder = IO.Path.GetFullPath(Application.StartupPath & "\Resources\")
Dim fileName = "book1.xlsx"
xlsWorkBook = xls.Workbooks.Open(resourcesFolder & fileName)
xlsWorkSheet = xlsWorkBook.Sheets("a")
xlsWorkSheet.Cells(1, 1) = TextBox1.Text
xlsWorkBook.SaveAs("C:\output\book1.xlsx")
xlsWorkBook.Close()
xls.Quit()
End Sub
i would like to change this path "C:\output\book1.xlsx" to save dialog, so i can choose where to save it manually.
thanks alot..
Like this, don't forget to dispose of com objects with the Marshal class like I added.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xls As New Microsoft.Office.Interop.Excel.Application
Dim xlsWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlsWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim resourcesFolder = IO.Path.GetFullPath(Application.StartupPath & "\Resources\")
Dim fileName = "book1.xlsx"
xlsWorkBook = xls.Workbooks.Open(resourcesFolder & fileName)
xlsWorkSheet = xlsWorkBook.Sheets("a")
xlsWorkSheet.Cells(1, 1) = TextBox1.Text
Using sfd As New SaveFileDialog
If sfd.ShowDialog() = DialogResult.OK Then
xlsWorkBook.SaveAs(sfd.FileName)
MessageBox.Show(sfd.Filename)
End If
End Using
xlsWorkBook.Close()
xls.Quit()
Marshal.FinalReleaseComObject(xlsWorkSheet)
Marshal.FinalReleaseComObject(xlsWorkBook)
Marshal.FinalReleaseComObject(xls)
End Sub
A little more comprehensive way to open the Save As Dialog than OneFineDay's answer (using the same method).
This opens the Save As dialog using a designated directory, filename, extension type, and window title; it also prompts before overwritting any existing files.
Dim dir as String = "C:\output\"
Dim fName As String = "Book1"
Using sfd As New SaveFileDialog
sfd.InitialDirectory = dir
sfd.Title = "Save As"
sfd.OverwritePrompt = True
sfd.FileName = fName
sfd.DefaultExt = ".xlsx"
sfd.Filter = "Excel Workbook(*.xlsx)|"
sfd.AddExtension = True
If sfd.ShowDialog() = DialogResult.OK Then
xlsWorkBook.SaveAs(sfd.FileName)
End If
End Using
Add an openfiledialog to your form and then ...
With OpenFileDialog1
.Title = " whatever"
.InitialDirectory = "c:\"
.Multiselect = False
If .ShowDialog() = DialogResult.OK Then
xlsWorkBook.SaveAs(.FileName)
End If
End With
You can use this :
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim xlsWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlsWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim xls As New Microsoft.Office.Interop.Excel.Application
Dim resourcesFolder = IO.Path.GetFullPath(Application.StartupPath & "\Resources\")
Dim fileName = "book1.xlsx"
xlsWorkBook = xls.Workbooks.Open(resourcesFolder & fileName)
xlsWorkSheet = xlsWorkBook.Sheets("a")
xlsWorkSheet.Cells(1, 1) = TextBox1.Text
xlsWorkBook.SaveAs("C:\output\book1.xlsx")
xls.Application.DisplayAlerts = False
xlsWorkBook.Close()
xls.Quit()
End Sub

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

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)

How to open a file using openfiledialog in vb.net?

How to open a file using openfiledialog
The below is my code:
Dim Fs As StreamReader
With OpenFD
.FileName = ""
.Title = "Open Text File"
.InitialDirectory = "c:\"
.Filter = "Text files|*.txt"
.ShowDialog()
End With
Dim path As String = OpenFD.FileName
txtin.Text = OpenFD.FileName
Fs = New StreamReader(path)
I can get the path of the file. But not able to open file. Can anyone help.
Thanks in advance
If you want to read the entire text file, you can use System.IO.File.ReadAllLines. You can do so like this:
Dim readText() As String = System.IO.File.ReadAllLines(path)
The file will then get stored into your string array, and you can access each line by index.
Try this. It should work.
Dim sr As StreamReader
'Supposing you haven't already set these properties...
With OFD
.FileName = ""
.Title = "Open a text file..."
.InitialDirectory = "C:\"
.Filter = "Text Files|*.txt"
End With
If OFD.ShowDialog() = DialogResult.OK Then
Try
sr = New StreamReader(OFD.Filename)
txtInFile.Text = OFD.Filename
Catch ex As Exception
MsgBox("The file specified could not be opened." & VbNewLine & "Error message:" & VbNewLine & VbNewLine & ex.Message, MsgBoxStyle.OK, "File Could Not Be Opened!")
End Try
End If
Do not use a stream to read a text file simply use File.ReadAllText(), here are my codes that work for me
Private Sub OpenFileButton_Click(sender As Object, e As EventArgs) Handles OpenFileButton.Click
OpenFileDialog1.Title = "Please Select TEXT File"
OpenFileDialog1.Filter = "Text File|*.txt"
OpenFileDialog1.FileName = "Query"
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
RichTextBox1.Text = File.ReadAllText(OpenFileDialog1.FileName)
End If
End Sub

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.