I'm trying to save data to an external data file on visual basic using visualstudio 2013, so far I've found various methods to do this but they all get stuck on the same problem
"An unhandled exception of type 'System.UnauthorizedAccessException' occurred in >mscorlib.dll
Additional information: Access to the path 'C:\test.txt' is denied."
The current method I'm using is the following code
Dim filename As String
filename = InputBox("Please Enter a Filename", "Enter Filename", "")
If filename = "" Then
MsgBox("Please Enter a value to save", vbOKOnly, "Error")
Else
filename = "C:\" + filename + ".txt"
File.WriteAllText(filename, "Accesories list Items")
End If
The Windows C Drive is inaccessible by any external program (pretty sure MS programs can access it). Try using "C:\temp\test.txt" If that fails then there is a problem. Otherwise it's probably because you're not allowed to access that area of Windows.
Related
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.
I would like to know how to check if the file name that is inserted from textbox exist in the same folder as the program itself.
For example, I'm going to enter notepad.exe into textbox then when you click the button it will check if that program exist on the folder where the program is. If I enter notepad.ex into textbox then it didn't find any file with that name, then it will give error.
Simply append a ".\" at the start of the filename, this will check on the current directory path, which always will be the same directory on which your main assembly is:
Dim filename As String = TextBox1.Text
If Not File.Exists(String.Format(".\{0}", filename)) Then
MessageBox.Show("File not found.", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
' File found.
End If
I suggest to use Directory.GetCurrentDirectory() only when you are not sure what the working directory is, for example when changed the default working directory path with Directory.SetCurrentDirectory() method.
I had to use this code to check if the file exist or not.
Dim currentPath As String = System.IO.Path.Combine(IO.Directory.GetCurrentDirectory(), Textbox1.Text)
If IO.File.Exists(currentPath) Then
..Do something here
Else
MsgBox("Executable doesn't exist!", vbOKOnly, "Error!")
End If
I'm using VBA for MS Access in order to link a small C# app to my database as a helper tool. I have tried a couple of different ideas from stackoverflow itself, including the ShellAndWait utility and another on that page.
I have a button on a form. When you click this button, it should run another application that I am currently storing in %APPDATA%/program/
This is the code that is currently active:
Private Sub BtnImport_Click()
Dim file As String
Dim hProcess as Long
file = Environ("APPDATA") & "\program\component_import.exe"
'This is the standard version, which apparently does nothing at this time.
hProcess = Shell(file, vbNormalFocus)
'This is the RunApplication version I got from here earlier. It ends
'with "Successfully returned -532462766
import_funcs.RunApplication(file)
'This is the ShellAndWait version, which gives me a "File not Found" error
import_funcs.ShellAndWait(file, 0, vbNormalFocus, AbandonWait)
End Sub
I had changed the original shell out for both the ShellAndWait module and another similar module. Neither of those options work any differently in terms of my application not starting.
I have double-checked that "file" is correct (It points to C:\Users\Me\AppData\Roaming\program\component_import.exe). I have double-checked to make sure that my app is in the correct location.
It runs fine if I double-click from file explorer. It says Run-time error '53': File not found. whenever I attempt to run it from MS Access.
Any suggestions?
Edit: As an aside, the path itself does not contain any spaces.
Edit: Added some additional code.
Link to first pastebin: RunApplication pastebin
Link to second pastebin: ShellAndWait pastebin
I found sometimes folder names with spaces throws error when using shell command.
eg: C:\My Folder\appl.exe
make it:
C:\MyFolder\appl.exe
Also can check for a valid path:
The following code checks the folder where chrome.exe residing and calling www.google.com from there by passing url as argument:
Public Sub Display_Google()
Dim chromePath As String
chromePath = "C:\Program Files\Google\Chrome\Application\chrome.exe"
If FileExists(chromePath) Then
Shell (chromePath & " -url" & " " & "www.google.com"), vbMaximizedFocus
Else
chromePath = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Shell (chromePath & " -url" & " " & "www.google.com"), vbMaximizedFocus
End If
End Sub
Public Function FileExists(ByVal FileName As String) As Boolean
On Error Resume Next
FileExists = Not CBool(GetAttr(FileName) And (vbDirectory Or vbVolume))
On Error GoTo 0
End Function
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.
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.