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.
Related
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
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 ...
I am trying to create a function that will allow user to upload multiple files to a local folder.
currently i am able to upload just one file. i needed to upload more files in one go.
what i use for opening files/folder
a.Multiselect = True
If a.ShowDialog() = Windows.Forms.DialogResult.OK Then
removeatt.Show()
removeatt.Text = "Remove Attachment"
fpath.Text = a.FileName
address.Text = System.IO.Path.GetFileName(a.FileName)
Dim file As String
file = fpath.Text.ToString
Label7.Text = file
If fpath.Text = "-" Then
removeatt.Hide()
Else
removeatt.Show()
End If
End If
what i use for saving attachment
If fpath.Text = "-" Then
Else
My.Computer.FileSystem.CopyFile(fpath.Text = "-", dir2 + Upload.Label16.Text, Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
End If
any help is appreciated
thanks
It is not entirely clear to me where you handle the selected files, the first one is about removing attachments and the saving-part is not about uploading, it saves a file to the disk of the user as it seems.
Generally i'd recommend you to write a function that handles one file at a time so you can feed the function with the list of files to be copied in a for each-loop. The function is a bit "basic" to demonstrate what i mean.
Public Function CopyToDisk(ByVal DestinationPath As String, ByVal Sourcepath As String) As String
If Not System.IO.File.Exists(Sourcepath) Then
Return "Source missing" & Sourcepath
End If
Try
File.Copy(Sourcepath, DestinationPath)
Catch ex As Exception
Return ex.Message
End Try
Return "ok"
End Function
Well, have a look at the example from MSDN here, it has a filepicker and then it puts the objects in an array you can loop through and copy it where you want it to copy.
Here is the MSDN-original
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
InitializeOpenFileDialog()
End Sub
Private Sub Selectfilebutton_Click_1(sender As Object, e As EventArgs) Handles Selectfilebutton.Click
Dim dr As DialogResult = Me.OpenFileDialog1.ShowDialog()
If (dr = System.Windows.Forms.DialogResult.OK) Then
' Read the files
Dim file As String
For Each file In OpenFileDialog1.FileNames
'' you can loop through the array of objects and use a function to do the copying
' so for instance with my function it would be :
' copytodisk(Destination, file.filename)
' Create a PictureBox for each file, and add that file to the FlowLayoutPanel.
Try
Dim pb As New PictureBox()
Dim loadedImage As Image = Image.FromFile(file)
pb.Height = loadedImage.Height
pb.Width = loadedImage.Width
pb.Image = loadedImage
FlowLayoutPanel1.Controls.Add(pb)
Catch SecEx As SecurityException
' The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. Please contact your administrator for details.\n\n" & _
"Error message: " & SecEx.Message & "\n\n" & _
"Details (send to Support):\n\n" & SecEx.StackTrace)
Catch ex As Exception
' Could not load the image - probably permissions-related.
MessageBox.Show(("Cannot display the image: " & file.Substring(file.LastIndexOf("\"c)) & _
". You may not have permission to read the file, or " + "it may be corrupt." _
& ControlChars.Lf & ControlChars.Lf & "Reported error: " & ex.Message))
End Try
Next file
End If
End Sub
Public Sub InitializeOpenFileDialog()
' Set the file dialog to filter for graphics files.
Me.OpenFileDialog1.Filter = _
"Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" + _
"All files (*.*)|*.*"
' Allow the user to select multiple images.
Me.OpenFileDialog1.Multiselect = True
Me.OpenFileDialog1.Title = "My Image Browser"
End Sub
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
I'm currently having the most irritating error in a program i'm making and i would seriously appreciate any help or advice that could help me fix it. The part of the program that i'm having a problem with is a form that loads up a selected image into a picturebox and then saves it into an MS Access database upon the click of the 'save' button. When executing the "Browse_Click" event, it prompts you to search for an image location and loads it into a picturebox (pbImage). This bit works fine and successfully loads it into it picturebox. The problem i'm having is when i try to save the image to my access database, i get the following argument exception error "The path is not of a legal form".
As far as i know all my code is fully functional because it previously worked, however an hour or two ago this error suddenly started appearing.
The first section of code below is what is executed when i want to load the picture into the picture box. The section below that is the 'save' code.
Public Class Manage_Cottages
Dim imgName As String
Dim daImage As OleDbDataAdapter
Dim dsImage As DataSet
Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
Dim dlgImage As FileDialog = New OpenFileDialog()
dlgImage.Filter = "Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif"
If dlgImage.ShowDialog() = DialogResult.OK Then
imgName = dlgImage.FileName
Dim selectedFileName As String = dlgImage.FileName
txtPath.Text = selectedFileName
Dim newimg As New Bitmap(imgName)
pbImage.SizeMode = PictureBoxSizeMode.StretchImage
pbImage.Image = DirectCast(newimg, Image)
End If
dlgImage = Nothing
imgName = " "
End Sub'
Save code
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim cnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=..\Debug\CourseworkDatabase.mdb"
Dim CN As New OleDbConnection(cnString)
CN.Open()
If imgName <> "" Then
Dim fs As FileStream
fs = New FileStream(imgName, FileMode.Open, FileAccess.Read) <----- where the error occurs.
Dim picByte As Byte() = New Byte(fs.Length - 1) {}
fs.Read(picByte, 0, System.Convert.ToInt32(fs.Length))
fs.Close()
Dim strSQL As String
strSQL = "INSERT INTO Cottage_Details([Image]) values (" & " #Img)"
Dim imgParam As New OleDbParameter()
imgParam.OleDbType = OleDbType.Binary
imgParam.ParameterName = "Img"
imgParam.Value = picByte
Dim cmd As New OleDbCommand(strSQL, CN)
cmd.Parameters.Add(imgParam)
cmd.ExecuteNonQuery()
MessageBox.Show("Image successfully saved.")
cmd.Dispose()
CN.Close()
End If
End Sub
Also below is the first couple of lines of what's displayed in the immediate window (not sure whether it will be of any help to diagnose the problem)
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll
System.Transactions Critical: 0 : http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/UnhandledUnhandled exceptionAlphaHolidayCottages.vshost.exeSystem.ArgumentException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089The path is not of a legal form. at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength)
Thanks for your time and help, would be over the moon if someone could help me resolve the issue.
Chris
You set imgName to " " at the end of btnBrowse_Click, so when you save the file under btnSave_Click you are trying to save it to the file name " ".
Try removing imgName = " " at the end of btnBrowse_Click, or assign imgName a proper file name before you save it.