I can't save specific file name using SaveFileDialog - vb.net

I can't save a file for example with name: ZK 10/2014. I noticed that a problem is with this sign: /. Why is that? Maybe it's from the other reason?
Here is my code:
Using SaveFileDialog1
With SaveFileDialog1
.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*"
.Title = "Save a file as"
.FileName = "Default1"
End With
Try
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
path = IO.Path.GetFullPath(SaveFileDialog1.FileName)
End If
If path <> "" Then
'Here I save a file using webservice's method'
End If
Catch ex As DirectoryNotFoundException
Logi.LogInfo(ex)
Catch ex As FileNotFoundException
Logi.LogInfo(ex)
Catch ex As Exception
Logi.LogInfo(ex)
End Try
End Using
When I set a file name to ZK 10/2014 I get MessageBox with this - File name is invalid. I want to use this name but I don't know what to change.

So, according to #Plutonix's and #Matt Wilko's comments filename cannot contain characters like: < > \ / | : * ? "
As #Matt Wilko said, here it is described - http://support2.microsoft.com/kb/177506

Related

How do I get a user to input a document and then save that document?

So I'm a bit stuck with my project, I am using Visual Studio and coding in Visual Basic, I am also using Microsoft Access with SQL if that helps at all.
What I need is to allow the user to select a document from an OpenFileDialog and to then save that document to the actual program so it is there when the program is next ran.
The following code is triggered on a button press, what I have so far is...
saveDocumentDialog.Filter = "Document Files|*.docx;*.doc;*.dot;*.txt;*.rtf;*.pdf;*.ppt;*.pptx;*.xls;*.xlsx"
saveDocumentDialog.FileName = "Untitled"
saveDocumentDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.Desktop
saveDocumentDialog.ShowDialog()
If saveDocumentDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
fullFilename = saveDocumentDialog.FileName
End If
Using openDocumentDialog As New SaveFileDialog
Dim filename As String = IO.Path.GetFileName(fullFilename)
openDocumentDialog.FileName = "Untitled"
openDocumentDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.Desktop
openDocumentDialog.Title = "Select Save Location"
openDocumentDialog.Filter = "All Files (*.*)|*.*"
If openDocumentDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
Try
My.Computer.FileSystem.CopyFile(fullFilename, openDocumentDialog.FileName)
Catch ex As Exception
MessageBox.Show("Could not copy the file." & Environment.NewLine & ex.Message, "Error copying file.", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
One way to do this is to designate a specific folder to the program(e.g. Public Documents), and save the files there and reload them from the folder when the program restarts. You could either hard code the path, or make a setting in the program for the user to specify a folder they would prefer.

How can I save user image and keep it in my application folder and display it?

i am trying to display the image in the PictureBox.
The user inputs his/her picture which I copy to the application folder ("Image"). When I try to display the path from the "Image" folder it returns always empty.
picturepath is the variable I use to store the path in my database.
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
PicturePath = "/images/" + correctfilename
FileToCopy = openFileDialog1.FileName
NewCopy = "C:\Users\nilraj\source\repos\caloriecal\caloriecal\Images\sss.jpg"
path = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10))
correctfilename = System.IO.Path.GetFileName(openFileDialog1.FileName)
System.IO.File.Copy(FileToCopy, path + "/Images/" + correctfilename)
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
TextBoxPictureFilePath.Text = ""
img = openFileDialog1.FileName
PictureBox1.Image = System.Drawing.Bitmap.FromFile(img)
TextBoxPictureFilePath.Text = openFileDialog1.FileName
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
I suggest to use Path.Combine to build your paths.
Your application directory is returned by Application.StartupPath, you just need to combine this path with a sub-path of choice to reference or create a Directory there.
You can then combine the this path with the OpenFileDialog.SafeFileName (the file name without the Path part), to create the final destination Path (event though Path.Combine can combine more that two components at a time, but here the Path without the file name is used to verify whether the destination Directory exists and, if not, create it. You could move this code somewhere else).
Note that I'm using an OpenFileDialog class here, not the Control. You can substitute the ofd object with your openFileDialog1 if you want.
Remember to filter the images types you want to handle.
Dim ofd = New OpenFileDialog()
If ofd.ShowDialog() <> DialogResult.OK Then Return
Try
Dim saveFilePath = Path.Combine(Application.StartupPath, "Images")
If Not Directory.Exists(saveFilePath) Then Directory.CreateDirectory(saveFilePath)
Dim saveFileName = Path.Combine(saveFilePath, ofd.SafeFileName)
File.Copy(ofd.FileName, saveFileName, True)
PictureBox1.Image?.Dispose()
PictureBox1.Image = New Bitmap(saveFileName, True)
TextBoxPictureFilePath.Text = ofd.FileName
Catch IOEx As IOException
MessageBox.Show("Cannot read file from disk. Original error: " & IOEx.Message)
Finally
ofd.Dispose()
End Try
If the VB.Net version in use doesn't handle this syntax: PictureBox1.Image?.Dispose(), use:
If PictureBox1.Image IsNot Nothing Then PictureBox1.Image.Dispose()
Since your images will be in the same relative path ([Application.StartupPath]\Images same as saveFilePath here), you can store in your DataBase just the image file name, then combine the file name with this Path.
Assign this Path to a Field, then combine it with any of the Images file names stored in the database to access the Bitmap.

VB.net, my code unable to run bat file

Dim app As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
If System.IO.Directory.Exists(app & "\Divers") Then
Try
Process.Start(app & "\Divers\b.bat")
cs.Text = "OK"
cs.Refresh()
Catch ex As Exception
eror.Text = "(B) Problems"
cs.Text = "error"
End Try
Try
Process.Start(app & "\Divers\Realtek\diver.exe")
d.Text = "OK"
Catch ex As Exception
DebugLog()
error.Text = "Driver Problems"
cs.Text = "error"
End Try
Try
Process.Start(app & "\Divers\a.bat")
CVS.Text = "OK"
Catch ex As Exception
error.Text = eror.Text & "(A) Problems"
cs.Text = "error"
End Try
And that is my code guys but the bat file is not working. Is opened but do nothing, if i open the bat file manual (with a mouse and double click logic!!!) its working. Please help
Your batch file may be working based on a working directory, and because you run the batch file with software that is in a different folder, the batch file's working directory does not match.
Put your software in the batch file folder and try again.

PC cannot print to Email using Outlook

I am having a very strange problem where one of the computers in our company is unable to print an MS Access report and attach it to an email. I have done a lot of research however most of it doesn't apply to my case as this issue is happening only on one PC out of the 20+ we have in the company. This is a print screen of the error we are getting:
The code I am using is the following:
If PrintMode = "Email" Then
Dim mAcc As New Access.Application
Dim DefaultPrinterName As New String("")
Dim PDFPrinterName As New String("")
Maintain__Loading.Setup()
Try
mAcc.CloseCurrentDatabase()
mAcc.DoCmd.Close()
System.Runtime.InteropServices.Marshal.ReleaseComObject(mAcc)
mAcc = Nothing
Catch ex As Exception
End Try
Dim startInfo As New ProcessStartInfo("C:\Program Files (x86)\PDFCreator\PDFCreator.exe") 'starts PDF Creator so it can save the report to PDF
startInfo.WindowStyle = ProcessWindowStyle.Minimized
Process.Start(startInfo)
AttachmentName = "C:\PDFs\pdf.pdf" 'PDF has been set up to save all files as TestPrint.pdf
PDFPrinterName = "PDFCreatorDistribution"
'------ GETS DEFAULT PRINTER NAME -------
Dim oPS As New System.Drawing.Printing.PrinterSettings
Try
DefaultPrinterName = oPS.PrinterName
Catch ex As System.Exception
DefaultPrinterName = ""
Finally
oPS = Nothing
End Try
'sets PDFCreatorDistribution as default printer
Shell(String.Format("rundll32 printui.dll,PrintUIEntry /y /n ""{0}""", PDFPrinterName))
Try
If Not UCase(Trim(Database)) = "TEST" Then
mAcc.OpenCurrentDatabase("R:\Distribution\Access\Distribution-Reports.mde")
Else
mAcc.OpenCurrentDatabase("R:\Distribution\Access\Test-Distribution-Reports.mde")
End If
Catch ex As Exception
MsgBox(Err.Description)
End Try
If IO.File.Exists(AttachmentName) Then 'if file exists it deletes it
IO.File.Delete(AttachmentName)
End If
Select Case Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("Passing1Type").Value.ToString)
Case "String"
mAcc.DoCmd.OpenReport(Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("MacroName").Value.ToString), Access.AcView.acViewPreview, , Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("Passing1").Value.ToString) & " = '" & Number & "'", Access.AcWindowMode.acWindowNormal)
Case "Numeric"
mAcc.DoCmd.OpenReport(Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("MacroName").Value.ToString), Access.AcView.acViewPreview, , Trim(Grid.Rows(Grid.CurrentRow.Index).Cells("Passing1").Value.ToString) & " = " & Number & "", Access.AcWindowMode.acWindowNormal)
End Select
mAcc.DoCmd.PrintOut()
mAcc.Visible = True
mAcc.CloseCurrentDatabase()
mAcc.DoCmd.Close()
System.Runtime.InteropServices.Marshal.ReleaseComObject(mAcc)
mAcc = Nothing
Do While Not System.IO.File.Exists("C:\PDFs\pdf.pdf")
Threading.Thread.Sleep(2000) 'if doesn't exist, wait for 2 seconds
If Not System.IO.File.Exists("C:\PDFs\pdf.pdf") Then 'if doesn't exist, wait for another 2 seconds
Threading.Thread.Sleep(2000)
End If
If Not System.IO.File.Exists("C:\PDFs\pdf.pdf") Then 'if doesn't exist, wait for another 2 seconds
Threading.Thread.Sleep(2000)
End If
If Not System.IO.File.Exists("C:\PDFs\pdf.pdf") Then 'shows error message
MsgBox("Error creating PDF. Please try again")
Exit Do
End If
Loop
'sets default printer name
Shell(String.Format("rundll32 printui.dll,PrintUIEntry /y /n ""{0}""", DefaultPrinterName))
'saves file as
Dim saveFileDialog As New SaveFileDialog()
saveFileDialog.Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*"
If saveFileDialog.ShowDialog() = DialogResult.OK Then 'if OK clicked
FileName = saveFileDialog.FileName 'get file name and move to new location/name
FileNameOnly = System.IO.Path.GetFileName(FileName)
Try
If IO.File.Exists(FileName) Then 'if file exists it deletes it before saving
IO.File.Delete(FileName)
End If
IO.File.Move(AttachmentName, FileName)
Catch ex As Exception
MsgBox(Err.Description)
Finally
Shell(String.Format("rundll32 printui.dll,PrintUIEntry /y /n ""{0}""", DefaultPrinterName))
End Try
Else 'user clicked cancel
FileName = ""
End If
Maintain__Loading.Dispose()
'GETS TO HERE AND AFTER THIS I GET THE ERROR MESSAGE DISPLAYED IN THE IMAGE ABOVE
If IO.File.Exists(FileName) Then
Try
Send_Email()
Catch ex As Exception
MsgBox(Err.Description)
End Try
Else
If Not FileName = "" Then MsgBox("An error has occured. Please try again")
End If
Shell(String.Format("rundll32 printui.dll,PrintUIEntry /y /n ""{0}""", DefaultPrinterName))
PhysicallyPrintedOrEmailed = True
End If 'Printmode = Email
I found a thread that I thought would solve my problem however unfortunately it didn't:
Unable to cast COM object - Microsoft outlook & C#
Any advice will be greatly appreciated
You have hardcoded the path to the program files location so if you are running this on a 32 bit machine it won't find the PDFCreator.exe.
Use Environment.GetFolderPath to find the path on the machine instead of hard coding it.`
Also it might help if you wrap the whole thing in a Try Catch block to see if there is an error somewhere you didn't expect
I have managed to solve this. Probably not the best way but we reinstalled Outlook and this solved the issue. We believe another program (most likely one that syncs Outlook contacts with phone) that has been installed has corrupted something. Thanks anyway :)

how to attach a file in vb.net email sending program?

I'm making a windows form.
Here is my current code:
I don't have any idea on how to link the open file dialog with the file that I am going to attach.
Try
With OpenFileDialog1
'OpenFileDialog1
.Filter = "Text files (*.txt)|*.txt|" & "All files|*.*"
If .ShowDialog() = DialogResult.OK Then
End If
End With
Catch
MsgBox("error occured!")
Something similar to..
Dim attach As MailAttachment = New MailAttachment(openFileDialog1.FileName)
Email.Attachments.Add(attach)