VB.NET 2008, Windows 7 and saving files - vb.net

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.

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.

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

how to open selected files through the default application of the file in VB 2010?

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.

Treeview -files & directories - Unauthorized Access Excpetion - vb.net

Okay, I still havenot figured out a way to resolve this problem. As simple as my program is, I am trying to list the directories in a treeview and then when an user clicks on it, I am listing all the files in an listview box. I am getting "Unauthorized Access Exception" when I click on 'My Document' folder and also on some other folders. How to resolve this? I am not even opening any files, just listing files from a directory I click on treeview.
When I use FolderBrowserDialog, I don't get this exception and am able to browse to MyDocuments Folder and even open a file.
Try
Dim strdirs() As String = IO.Directory.GetDirectories(ds)
tv1_temp(arr_ind(0)).Nodes.clear()
For Each d As String In strdirs
Dim ss = d.Substring(d.LastIndexOf(IO.Path.AltDirectorySeparatorChar) + 1)
Dim tn = New TreeNode(ss)
tn.Name = ss
tv1_temp(arr_ind(0)).Nodes.Add(tn)
Next
tv1_temp(arr_ind(0)).ExpandAll()
Catch ex As IO.IOException
Comment.Text = "Device not ready!"
Catch ex As System.UnauthorizedAccessException
Comment.Text = ("Unauthorized Access to this directory!")
End Try
Thank you!

Catching events after calling the FileSystem.FileCopy UI dialog

I copy some files to some destination and in the meantime I want to log the file names in a text file.
I'd like to use the Windows 7 Copy/Replace dialog in the case the files are already present in the destination folder (to keep users in a "known" environment).
But my problem is that I am not able to catch the 4 different events depending on the user's choice :
Replace
Do not copy
Copy with a different name
Cancel (for this one I can throw an exception and catch it)
Dim oFile As New StreamWriter(strTextFile)
For Each p In Me.Files ' List of custom class with file information like Path, Extension, etc...
Dim strFileName = Path.Combine(strDestinationFolder, p.FileName)
If File.Exists(strFileName) Then
Try
My.Computer.FileSystem.CopyFile(p.Path, strFileName, UIOption.AllDialogs, UICancelOption.ThrowException)
Catch ex As Exception
' I would like to catch user's choices here to react accordingly in the text file
End Try
Else
oFile.WriteLine(p.Path & ";" & p.FileName)
End If
Next
oFile.Close()
Thanks in advance.