how to open selected files through the default application of the file in VB 2010? - vb.net

I have Windows application written in VB 2010.Here, user may select any file from open dialog.So, I want to open the file in corresponding application.for example, suppose user selecting docx file then i have to open the file using msword,suppose,if it is a pdf file, then i have to open with adobe reader or available pdf reader(default application).
Is this possible to do?

Shell and the Windows API CreateProcess() are for starting executable files.
If you're loading a document/file then these are handled by ShellExecute() and can be initiated in .NET using the Process.UseShellExecute property:
Private Function ShellExecute(ByVal File As String) As Boolean
Dim myProcess As New Process
myProcess.StartInfo.FileName = File
myProcess.StartInfo.UseShellExecute = True
myProcess.StartInfo.RedirectStandardOutput = False
myProcess.Start()
myProcess.Dispose()
End Function
Taken from the #VB wiki.

Try this:
now with openfiledialog
Dim OpenFileDlg as new OpenFileDialog.
OpenFileDlg.FileName = "" ' Default file name
OpenFileDlg.DefaultExt = ".xlsx" ' Default file extension
OpenFileDlg.Filter = "Excel Documents (*.XLSX)|*.XLSX"
OpenFileDlg.Multiselect = True
OpenFileDlg.RestoreDirectory = True
' Show open file dialog box
Dim result? As Boolean = OpenFileDlg.ShowDialog()
' Process open file dialog box results
for each path in OpenFileDlg.Filenames
Try
System.Diagnostics.Process.Start(Path)
Catch ex As Exception
MsgBox("Unable to load the file. Maybe it was deleted?")
End Try
If result = True Then
' Open document
Else
Exit Sub
End If
next
This will work if the file is registered with the OS. Use Try catch because it can throw errors if the file is in use.
Edit: It uses always the default application.

Related

Why does File.Open() not open the file?

I am implementing a Save File button in my VB.NET Windows Forms application.
I am attempting to encapsulate the normally expected behaviour of Save buttons in Windows applications. I.E: If a file was already selected then open the current file it, write to it and save it; else if there is no current file, or Save As was used, then show a SaveFileDialog, then open, write and save just the same.
I currently have coded the function below but I keep getting an exception:
Cannot access a closed file
The file is created just fine, but is empty (It should contain "Test string"). I can't understand how the file is closed unless some kind of garbage collection is doing away with it somehow??
The current code:
Function SaveFile(ByVal Type As ProfileType, ByVal suggestedFileName As String, ByVal saveAs As Boolean, ByVal writeData As String) As Boolean
Dim FileStream As Stream = Nothing
Dim FolderPath As String = Nothing
Dim CancelSave As Boolean = False
Dim SaveFileDialog As SaveFileDialog = New SaveFileDialog()
Try
If Type = ProfileType.Product Then 'Select the initial directory path
FolderPath = ProductPath
Else
FolderPath = ProfilePath
End If
If (FileName = String.Empty Or saveAs = True) Then 'If a file is not already selected launch a dialog to allow the user to select one
With SaveFileDialog
.Title = "Save"
.AddExtension = True
.CheckPathExists = True
.CreatePrompt = False
.DefaultExt = "xml"
.Filter = "Xml Files (*.xml)|*.xml"
.FilterIndex = 0
.FileName = suggestedFileName
.InitialDirectory = FolderPath
If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
FullyQualfiedPathName = New String(SaveFileDialog.FileName) 'Save the path and name of the file
FileName = Path.GetFileName(FullyQualfiedPathName)
Else
CancelSave = True
End If
.Dispose()
End With
End If
If (FileName <> String.Empty) Then 'Write the string to the file if the filewas correctly selected
FileStream = File.Open(FullyQualfiedPathName, FileMode.OpenOrCreate, FileAccess.ReadWrite) 'Open the file
Using FileStreamWriter As New StreamWriter(FileStream) 'Create the stream writer
FileStreamWriter.Write(writeData) 'Write the data
FileStream.Close() 'Clse the file
End Using
ElseIf (CancelSave <> True) Then 'Only throw an exception if the user *didn't* cancel the SavefileDialog
Throw New Exception("File stream was nothing", New IOException())
End If
Catch ex As Exception
MessageBox.Show(ex.Message & Environment.NewLine & FullyQualfiedPathName)
End Try
Return True
End Function
One problem I see is that you should be putting your File.Open in a Using block:
Using fs = File.Open(fullyQualfiedPathName, FileMode.OpenOrCreate, FileAccess.ReadWrite)
Using writer As New StreamWriter(fs) 'Create the stream writer
writer.Write(writeData) 'Write the data
'fs.Close() <--- you do not need this line becuase the "Using" block will take care of this for you.
End Using
End Using
I'm not sure if this will resolve your issue because I can't run your code, but the Using block will automatically take care of closing and cleaning up disposable instances like FileStream and StreamWriter, even if an exception is thrown.
By the way, you should use proper naming conventions (lower camel case) for local variables.

Unhandled exception has occured in the application vb.net

Ok, so my code look like the following.
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("E:/Med/Dra.txt", False)
file.WriteLine(NameBasic)
file.WriteLine(LastBasic)
file.WriteLine(PhoneBasic)
file.Close();
All those are variables that I have set for text boxes. This is OnbuttonClick(...
Now for my onload I take the info out of the notepad, Here is the code,
Dim read As System.IO.StreamReader
read = My.Computer.FileSystem.OpenTextFileReader("E:/Med/Dra.txt")
lblNameBasic.Text = read.ReadLine
lblLastBasic.Text = read.ReadLine
lblPhoneBasic.Text = read.ReadLine
read.Close();
I have placed the notepad(txt file) inside a flashdrive folder named med
I got the saving info to work and load, so I took the flashdrive to another computer, I got this nasty error, talking about the System.IO and all this other stuff.
It then prompts me, would you like to continue with errors, or quit.
I click continue than all the saved data does not load. Am I doing something wrong here??
Also sorry for alot of questions today. (The .exe is in the flashdrive, med folder aswell).
First of all, your path is incorrect - E:/Med/Dra.txt should be E:\Med\Dra.txt. And here how you use open file dialog - this is just basis, you need to take care of error handling, etc.
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "txt files (*.txt)|*.txt"
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim read As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(openFileDialog1.FileName)
End If
I think, main reason why you had errors is because incorrect path. You can also check if path exists
If Not File.Exists("E:\Med\Dra.txt") Then
MessageBox.Show("There is no such file")
Exit Sub
End If
' Code to open non existing file will be skipped

Exporting pdf file using Crystal report (Allow user to choose file path)?

I know how to export to pdf using Crystal Report, but I don't want to preset file path, I want users can choose file path (and file name) when clicking Export button.
Do you know how to do that ?
Thank you very much,
Tai
Prompting the user for a save location would be something you'd implement as part of your app - this related question provides some answers on how to do that. Then, you'd just supply the path from the dialog to the Crystal Reports export API so it saves to that location.
Here is a partial code in my project. I hope it helps.
Dim saveFileDialog1 As New SaveFileDialog()
'saveFileDialog1.InitialDirectory = My.Computer.FileSystem.CurrentDirectory
saveFileDialog1.Filter = "PDF files (*.PDF)|*.PDF"
saveFileDialog1.FilterIndex = 1
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
'Here is where you write the file
Catch Ex As Exception
'MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
End Try
End If

Use Shell32.dll on mix of XP, Vista, Win7 via XCOPY deploy

I'm trying to use Shell32.dll to unzip a simple compressed file. I have a reference to Shell32.dll which shows up as Interop.Shell.dll on my development PC (Win7 64.) I push exe updates out via file copy from a central location and I would like to do this for the .dll as well.
The program fails on XP using the same file as it installed on my PC. I tried using a Shell.dll from the XP \Windows\System renamed to Interop.Shell.dll but I guess that would be to simple - it gets an error that it cannot load when I try to invoke the dll.
I'm open too another way of doing unzip that uses a dll that is agnostic as to platform. I've used 7Zip via Process.Start() but I'd like to avoid having to install/update a program on the clients.
Is there a common denominator Shell32.dll I could use the would run on any Win OS on/after XP?
Or do I have to create a separate build for each OS if I use Shell32.dll?
Thanks!
Function Unzip(FilePathofZip As String, DestinationFolder As String) As Boolean
Try
Dim sFile As String = FilePathofZip
' requires referenc to windows.system.shell32.dll
Dim sc As New Shell32.Shell()
If IO.Directory.Exists(DestinationFolder) Then IO.Directory.Delete(DestinationFolder, True)
Application.DoEvents()
IO.Directory.CreateDirectory(DestinationFolder)
'Declare the folder where the files will be extracted
Dim output As Shell32.Folder = sc.NameSpace(DestinationFolder)
If FilePathofZip.EndsWith(".kmz") Then
sFile = FilePathofZip & ".zip"
IO.File.Move(FilePathofZip, sFile)
Application.DoEvents()
End If
'Declare your input zip file as folder
Dim input As Shell32.Folder = sc.NameSpace(sFile)
'Extract the files from the zip file using the CopyHere command .
output.CopyHere(input.Items, 4)
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
I switched to DotNetZip. Add Project Reference to the Ionic.Zip.Reduced.dll. Imports Ionic.Zip
This code is expecting .kmz files downloaded from ESRI REST services but should work with .zip files as well.
Function Unzip(FilePathofZip As String, DestinationFolder As String) As Boolean
' extract .kmz files downloaded from ESRI REST services
Try
Dim sFile As String = FilePathofZip
If IO.Directory.Exists(DestinationFolder) Then IO.Directory.Delete(DestinationFolder, True)
Application.DoEvents()
IO.Directory.CreateDirectory(DestinationFolder)
If FilePathofZip.EndsWith(".kmz") Then
sFile = FilePathofZip & ".zip"
IO.File.Move(FilePathofZip, sFile)
Application.DoEvents()
End If
Try
' Using... required
Using zip As ZipFile = ZipFile.Read(sFile)
Dim e As ZipEntry
For Each e In zip
e.Extract(DestinationFolder)
Next
End Using
Catch ex1 As Exception
MsgBox("Problem with compressed file - notify programmers" & vbCrLf & ex1.Message)
Return False
End Try
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function

VB.NET 2008, Windows 7 and saving files

We have to learn VB.NET for the semester, my experience lies mainly with C# - not that this should make a difference to this particular problem.
I've used just about the most simple way to save a file using the .NET framework, but Windows 7 won't let me save the file anywhere (or anywhere that I have found yet). Here is the code I am using to save a text file.
Dim dialog As FolderBrowserDialog = New FolderBrowserDialog()
Dim saveLocation As String = dialog.SelectedPath
... Build up output string ...
Try
' Try to write the file.
My.Computer.FileSystem.WriteAllText(saveLocation, output, False)
Catch PermissionEx As UnauthorizedAccessException
' We do not have permissions to save in this folder.
MessageBox.Show("Do not have permissions to save file to the folder specified. Please try saving somewhere different.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch Ex As Exception
' Catch any exceptions that occured when trying to write the file.
MessageBox.Show("Writing the file was not successful.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
The problem is that this using this code throws an UnauthorizedAccessException no matter where I try to save the file. I've tried running the .exe file as administrator, and the IDE as administrator.
Is this just Windows 7 being overprotective? And if so, what can I do to solve this problem? The requirements state that I be able to save a file!
Thanks.
This code:
Dim dialog As FolderBrowserDialog = New FolderBrowserDialog()
Dim saveLocation As String = dialog.SelectedPath
Is giving you the location of a folder. Then you're trying to save a file with the same name as the folder. Instead, I assume you want to save a file inside that folder:
Dim saveLocation As String = dialog.SelectedPath
saveLocation = Path.Combine(saveLocation, "SomeFile.txt")
That will create a file called "SomeFile.txt" inside the selected folder.
Alternatively, instead of using FolderBrowserDialog to choose a folder, use SaveFileDialog to select the actual file instead.