Allowing multiple files to be processed through one module - vb.net

I've created a program to modify security settings of a .pdf file.
This works fine for one file - but I want to allow editing multiple .pdf's with the touch of one button and am struggling to make it work.
I have pasted the code for my GUI below, "Modify_PDF" is the module that runs the pdf security modification code. Is it possible to run multiple files through this module from here?
Dim source_file As String = ""
''' Handles clicking of the 'Open file' button
Private Sub open_button_Click(sender As System.Object, e As System.EventArgs) Handles open_button.Click
Dim input As FileStream = Nothing
'Set filter to only allow compatible files
OpenFileDialog.Filter = "PDF documents (*.pdf)|*.pdf"
'Allow multiple files to be opened
OpenFileDialog.Multiselect = True
'open the file selection dialogue
If OpenFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
input = OpenFileDialog.OpenFile()
Catch Ex As Exception
MsgBox("Error opening file: " & vbCrLf & Ex.Message)
Finally
'Check this again to ensure no exception on open.
If (input IsNot Nothing) Then
input.Close()
End If
End Try
If input IsNot Nothing Then
source_file = OpenFileDialog.FileName
If Modify_PDF.process_file(source_file, "") Then
PDF_name.Text = Path.GetFileName(OpenFileDialog.FileName)
input.Close()
modify_button.Enabled = Modify_PDF.process_file(source_file, "") 'Allow report to be created if processing succeeds
End If
End If
End If
End Sub
''' Handles clicking of the 'Modify PDF' button
Private Sub generate_button_Click(sender As System.Object, e As System.EventArgs) Handles modify_button.Click
Modify_PDF.modify_pdf(source_file, source_file, "")
End Sub

Try it like this:
If OpenFileDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
For Each FileName as String in OpenFileDialog.FileNames
'Do something with the filename here
Next
Catch ...

Related

Limited Multiselect in open file dialog?

I want the user to have the option to select multiple files through openfiledialog which I have in my code, but then if the user selects a file from one folder he is then restricted to select another file only from this specific folder. What is the best way to approach to this problem?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim openfiledialog1 As New OpenFileDialog
With openfiledialog1
.Title = "Select your models"
.Filter = "Solidworks Files|*.sldprt;"
.Multiselect = True
End With
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
For Each mfile As String In openfiledialog1.FileNames
'' Add all filenames in a txt file, in a column
Next
End If
End Sub
As far as I know, OpenFileDialog doesn't offer a way to prevent the user from navigating to another directory.
One approach would be to create a class-level variable that holds the value of the recently used directory path. Then, whenever a new file is selected, you check its directory path against the one previously stored. If it matches, continue. If not, break the operation and report to the user.
Here's a complete example:
Private openFileDialog1 As New OpenFileDialog
Private modelsDirectory As String = Nothing
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With openFileDialog1
.Title = "Select your models"
.Filter = "Solidworks Files|*.sldprt;"
.Multiselect = True
.FileName = Nothing
' Open the dialog and navigate to the previous direcoty by default.
.InitialDirectory = modelsDirectory
End With
If openFileDialog1.ShowDialog <> DialogResult.OK Then Exit Sub
Dim dirPath As String = IO.Path.GetDirectoryName(openFileDialog1.FileName)
If modelsDirectory IsNot Nothing AndAlso
Not dirPath.Equals(modelsDirectory, StringComparison.OrdinalIgnoreCase) Then
MessageBox.Show("Models must be selected from the following directory:" &
vbNewLine & modelsDirectory, "Restricted Directory")
Exit Sub
End If
' Store the value of the current directory path.
modelsDirectory = dirPath
For Each filePath As String In openFileDialog1.FileNames
' TODO: use the selected files as you see fit.
Next
End Sub
You might want to remove this restriction at some point (e.g., if you clear the list of selected files). You can achieve that by simply setting modelsDirectory to Nothing:
Private Sub ClearFilesList
' TODO: clear the files.
modelsDirectory = Nothing
End Sub

closing mdi child form causes System.ObjectDisposedException

i created a mdi database application. One child form has a datagridview. when clicking on a button on that form a new form opens with a pdfviewer(AxAcroPDF1) on it. This form shows a pdf document stored in the sql server database.
closing this form is done by Me.Close(). It closes it, but when i do it several times, opening that form and closing it, then at one point i get a
System.ObjectDisposedException which says Cannot access a disposed object and it isn't caught either in the try catch block.
It also says The application is in break mode. Your app has entered a break state, but there is no code to show because all threads where executing external code(typically system or framwork code)
Never experienced this kind of problem before.
Here is the code to launch the form with the pdf viewer
Private Sub btnShowDocument_Click(sender As Object, e As EventArgs) Handles btnShowDocument.Click
frmDocument = New frmShowDocumentatie
rowIndex = dgvData.CurrentRow.Index
FileName = dgvData.Item(6, rowIndex).Value
If FileName = "" Then
MessageBox.Show("Can't open documentation" & vbNewLine & "File doesn't exist", "Database Info", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
frmDocument.Show()
End If
End Sub
And here's the form that opens up then
Imports System.Data.SqlClient
Public Class frmShowDocumentatie
'local variables to get passed the public shared values from
'curent selected row index and document name in datagridview
Private iRow As Integer
Private fName As String
Private Sub frmShowDocumentatie_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'sets the mdi parent
MdiParent = MDIParent1
'sets the text of the form to the filename of pdf bestand
Me.Text = "Document: " & getFilename()
'loads the pdf bestand, need the filepath which is provided by getfilepath function
AxAcroPDF1.src = GetFilePath()
'gets the values from the selected row index and corrsponding filename
iRow = frmDataView.rowIndex
fName = frmDataView.FileName
tsmiDocument.Text = "Document: " & getFilename()
End Sub
'function for getting the filename of selected pdf file in datagridview
Public Function getFilename() As String
fName = frmDataView.FileName
getFilename = fName
End Function
'gets the file path of selected pdf bestand
Function GetFilePath() As String
'Dim i As Integer = frmVerledenOverzicht.dgvData.CurrentRow.Index
'Dim filename As String = frmVerledenOverzicht.dgvData.Item(6, i).Value
Dim sFilePath As String
Dim buffer As Byte()
Using conn As New SqlConnection("Server=.\SQLEXPRESS;Initial Catalog=AndriesKamminga;Integrated Security=True;Pooling=False")
conn.Open()
Using cmd As New SqlCommand("Select Bestand From dbo.PaVerledenOverzicht WHERE Documentatie =" & "'" & getFilename() & "';", conn)
buffer = cmd.ExecuteScalar()
End Using
conn.Close()
End Using
sFilePath = System.IO.Path.GetTempFileName()
System.IO.File.Move(sFilePath, System.IO.Path.ChangeExtension(sFilePath, ".pdf"))
sFilePath = System.IO.Path.ChangeExtension(sFilePath, ".pdf")
System.IO.File.WriteAllBytes(sFilePath, buffer)
'returns the file path needed for AxAcroPDF1
GetFilePath = sFilePath
End Function
Private Sub tsmiSluiten_Click(sender As Object, e As EventArgs) Handles tsmiSluiten.Click
Try
Me.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Database Info", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
End Class
anyone knows what's causing this exception and why is the program crashing instead of being caught in the try catch block
Am using visual studio community edition 2017

Import CSV file to database using VB

I need to import the information from a CSV txt file to a database using the DataGridView in my form. The application should allow the user to open a .txt file and then update the DataGridView table in my form. I am able to get the file, but am unable to update the grid using the file. I can update textboxes, but cannot figure out how to update the grid. Can anyone help me out with this?
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Public Class Form1
Private fileToOpen As String 'the file to be opened and read
Private responseFileDialog As DialogResult 'response from OpenFileDialog
Private myStreamReader As StreamReader 'the reader object to get contents of file
Private myStreamWriter As StreamWriter 'the writer object to save contents of textbox
Private myTextFieldParser As TextFieldParser ' To parse text to searched.
Dim myDataAdapter As OleDb.OleDbDataAdapter
Dim myString() As String
Dim myRow As DataRow
Private Sub PeopleBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles PeopleBindingNavigatorSaveItem.Click
Me.Validate()
Me.PeopleBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.MyContactsDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyContactsDataSet.People' table. You can move, or remove it, as needed.
Me.PeopleTableAdapter.Fill(Me.MyContactsDataSet.People)
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim fileContentString As String 'contents of the file
Dim update As New OleDb.OleDbCommandBuilder(myDataAdapter)
'Dim myRow As DataRow
'set the properties of the OpenFileDialog object
OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.CurrentDirectory
OpenFileDialog1.Title = "Select File to View..."
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
'responseFileDialog contains holds the response of the user (which button they selected)
responseFileDialog = OpenFileDialog1.ShowDialog()
'check to see if the user select OKAY, if not they selected CANCEL so don't open anything
If (responseFileDialog <> System.Windows.Forms.DialogResult.Cancel) Then
'make sure there isn't a file already open, if there is then close it
If (myStreamReader IsNot Nothing) Then
myStreamReader.Close()
'TextBoxFileOutput.Clear()
End If
'open the file and read its text and display in the textbox
fileToOpen = OpenFileDialog1.FileName
myStreamReader = New StreamReader(OpenFileDialog1.FileName)
initTextFieldParser()
'loop through the file reading its text and adding it to the textbox on the form
Do Until myStreamReader.Peek = -1
fileContentString = myStreamReader.ReadLine()
'Try
' myTextFieldParser = New TextFieldParser(fileToOpen)
' myTextFieldParser.TextFieldType = FieldType.Delimited
' myTextFieldParser.SetDelimiters(",")
'Catch ex As Exception
' MessageBox.Show("Cannot Open File to Be Read!")
'End Try
myTextFieldParser.TextFieldType = FieldType.Delimited
myString = TextFieldParser.NewLine()
myRow.Item("FirstName") = myString(1)
MyContactsDataSet.Tables("People").Rows.Add(myRow)
PeopleTableAdapter.Update(MyContactsDataSet)
'TextBoxFileOutput.AppendText(fileContentString)
'TextBoxFileOutput.AppendText(Environment.NewLine)
Loop
'close the StreamReader now that we are done with it
myStreamReader.Close()
'SaveToolStripMenuItem.Enabled = True
End If
End Sub
Private Sub initTextFieldParser()
'Close myTextFieldParser in case the user is surfing through the records and then
'decides to search for a particular last name --> Basically start searching from beginning of the file
If (myTextFieldParser IsNot Nothing) Then
myTextFieldParser.Close()
End If
Try
myTextFieldParser = New TextFieldParser(fileToOpen)
myTextFieldParser.TextFieldType = FieldType.Delimited
myTextFieldParser.SetDelimiters(",")
Catch ex As Exception
MessageBox.Show("Cannot Open File to Be Read!")
End Try
End Sub
End Class
updating gridview with your file content
Import System.IO as we gonna need StreamReader
Using reader As New StreamReader("filepath")
DataGridView1.Columns.Add("col1",reader.ReadToEnd())
End Using
check this out!

StreamWriter leaving a file even if not saved

I have this code to write some data from textboxes into a textfile. And i'm using streamwriter to do this. Here you may see the code below:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim Save As New SaveFileDialog()
Dim myStreamWriter As System.IO.StreamWriter
Save.Filter = "Text [*.txt*]|*.txt|All Files [*.*]|*.*"
Save.CheckPathExists = True
Save.Title = "Export & Save - FNG"
Save.FileName = txtTitle.Text & " - Plugs Details File Exported"
Save.ShowDialog(Me)
Try
myStreamWriter = System.IO.File.AppendText(Save.FileName)
myStreamWriter.Write("Details of Plugs:" & Environment.NewLine & txtDetails.Text & Environment.NewLine & DateAndTime.Now)
myStreamWriter.Flush()
Catch ex As Exception
End Try
End Sub
The code does work fine, it saves the details into a text file too. But the problem is when i cancel the save file dialog (without saving the textfile) it stil creates a file in the application start path. Why is this happening? What am i doing wrong? How do i correct this?
Try
If Save.ShowDialog(Me) <> DialogResult.Ok Then Return
Cancelling the dialog doesn't automatically make your Sub return!
Further, you are using StreamWriter wrong. Use
Using myStreamWriter As System.IO.StreamWriter = System.IO.File.AppendText(Save.FileName)
myStreamWriter.Write("Details of Pish flaps:" & Environment.NewLine & txtDetails.Text & Environment.NewLine & DateAndTime.Now)
End Using
And remove the Dim of the StreamWriter. This will ensure that the StreamWriter is closed even if an exception is thrown.

vb..NET Pause/Resume a file copy (like windows 8 button)

Can we PAUSE and RESUME a file copy ?
Using :
3 Button_
1 OpenFileDialog_
1 FolderBrowserDialog
Imports :
Imports System.IO
Code :
Private Sub BTN_filedialog_Click(sender As Object, e As EventArgs) Handles BTN_filedialog.Click
OpenFileDialog1.InitialDirectory = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" 'Cette clé de registre ouvre "Ordinateur"
OpenFileDialog1.Title =
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = _
"All files (*.*)|*.*|txt files (*.txt)|*.txt"
Dim dlgResult = OpenFileDialog1.ShowDialog()
If dlgResult <> System.Windows.Forms.DialogResult.OK Then
MessageBox.Show("File Error " & dlgResult)
End If
End Sub
Private Sub BTN_folderbrowserdialog_Click(sender As Object, e As EventArgs) Handles BTN_folderbrowserdialog.Click
Dim dlgResult = FolderBrowserDialog1.ShowDialog()
If dlgResult <> System.Windows.Forms.DialogResult.OK Then
MessageBox.Show("Folder Error " & dlgResult)
End If
End Sub
Private Sub BTN_copyfile_Click(sender As Object, e As EventArgs) Handles BTN_copyfile.Click
My.Computer.FileSystem.CopyFile( _
OpenFileDialog1.FileName, _
FolderBrowserDialog1.SelectedPath & "\" & _
OpenFileDialog1.SafeFileName, _
FileIO.UIOption.AllDialogs)
End Sub
I use My.Computer.FileSystem.CopyFile
With Windows 8, inside the dialog box "copy", there is a pause button.
How to call this "event" ?
I do not know if this is possible, but can we send parameters to a certain Lib /. Dll to simulate the action of pressing the pause button ?
Ps : Sorry for my bad english, i'm french.
The best way to approach this would be to ignore the FileSystem.CopyFile command completely. Instead, use a FileStream to open the file you wish to copy, read the bytes, create a new file to the target destination, and write the bytes to that location.
You can read and write the file in smaller chunks so that you can check to see if a pause variable is set to true. For example, if you create a pause button, set a global variable "bCopyPaused = true". In the custom copy function you can use a simple if statement and check if bCopyPaused == true and pause the operation. You'll need to keep track of the last copied or written bytes to allow the operation to be resumed.
Here's some examples of using FileStream: http://vb.net-informations.com/files/vb.net_FileStream.htm