Create file causes access denied in vb.net - vb.net

I was trying to create function which will create a file in a specific folder. But every time when I am trying to create the file, it will shows me access denied. I have read a lot of solution, but i still have no clue on how to solving the problems.
Dim x as string
x = Path.GetDirectoryName(Application.ExecutablePath)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles APIsaveBtn.Click
SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*|CSV Files (*.csv)|*.csv"
SaveFileDialog1.FileName = ""
Dim newArray As New ArrayList()
Dim path As String = x
If File.Exists(path) = True Then
System.IO.File.WriteAllText(path, "")
newArray.Sort()
My.Settings.API_Path = path
My.Settings.API_Key = APIkeyTxtBox.Text
Using sw As StreamWriter = New StreamWriter(path, True)
sw.WriteLine(APIkeyTxtBox.Text)
End Using
apikey = APIkeyTxtBox.Text
MessageBox.Show("Save Sucessfully", "Save")
ElseIf File.Exists(path) = False Then
Dim newFile As IO.StreamWriter = System.IO.File.CreateText(path)
newFile.Close()
My.Settings.API_Path = path
My.Settings.API_Key = APIkeyTxtBox.Text
Using sw As StreamWriter = New StreamWriter(path, True)
sw.WriteLine(APIkeyTxtBox.Text)
End Using
apikey = APIkeyTxtBox.Text
MessageBox.Show("Save Sucessfully", "Save")
End If
I have no idea on how to give permission to allow create file a specific folder.

Related

Changing the Name of a File Selected in FileDialog

I am trying to make an application which takes a file from your computer, renames that file with variables from 4 different combo boxes and then uploads it to an FTP server.
I have gotten everything working except the renaming part....
what i am trying to do is this.
slectedFile.pdf would become combobox1_combobox2_combobox3_combobox4.pdf
The file path is stored in a variable named FileName i know how to update FileName with the combobox values, but does it keep the original Path?
How would i go about doing this?
This is the code i have so far.
IP_box, User_Box and Pass_box are the textboxes for the appropriate server information.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(IP_Box.Text.ToString), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential(User_Box.Text.ToString, Pass_Box.Text.ToString)
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte
Try
System.IO.File.ReadAllBytes(FileName)
Catch ex As Exception
MessageBox.Show(ex.Message)
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
End Sub
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Filename = System.IO.Path.GetFullPath(FD.FileName)
End If
End Function
Thank you in advance
At the end of your subroutine, you try to retrieve the file; you incorrectly use System.IO.Path.GetFullPath(FD.FileName) as FD.FileName already provides the full file name.
In order to rename the file to your desired name, you need to firstly evaluate the values of each ComboBox, of which can be done as a loop:
Private Function enumerateCheckboxes(ByVal path As String)
Dim fName As String
For Each Control In Me.Controls
If (TypeOf Control Is CheckBox AndAlso DirectCast(Control, CheckBox).Checked) Then
fName += CStr(Control.Name) + "_"
End If
Next
fName = path + fName.Substring(0, fName.Length - 1) + ".pdf"
Return fName
End Function
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Dim Filename As String = FD.FileName
Filename = StrReverse(Filename)
Filename = Mid(Filename, InStr(Filename, "\"), Len(Filename))
Filename = StrReverse(Filename)
Return Filename
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
OpenDialog()
End Sub
If I test with a file from the desktop:
However now we might possibly have an issue that the file does not exist, thus the program will crash. To fix this, we can quickly rename the file for the upload, and rename it back when it's finished.
The complete code:
Imports System.IO
Public Class Form1
Dim Filename As String
Dim originalFile As String
Public Function OpenDialog()
Dim FD As OpenFileDialog = New OpenFileDialog()
FD.Title = "Selecteer een bestand"
FD.InitialDirectory = "C:\"
FD.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
FD.FilterIndex = 2
FD.RestoreDirectory = True
If FD.ShowDialog() = DialogResult.OK Then
Filename = FD.FileName
Filename = StrReverse(Filename)
Filename = Mid(Filename, InStr(Filename, "\"), Len(Filename))
Filename = StrReverse(Filename)
Return Filename
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(IP_Box.Text.ToString), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential(User_Box.Text.ToString, Pass_Box.Text.ToString)
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte
Try
Filename = OpenDialog()
System.IO.File.ReadAllBytes(Filename)
Catch ex As Exception
MessageBox.Show(ex.Message)
MessageBox.Show("Stack Trace: " & vbCrLf & ex.StackTrace)
End Try
FileSystem.Rename(originalFile, Filename)
Dim strz As System.IO.Stream = request.GetRequestStream()
strz.Write(file, 0, file.Length)
strz.Close()
strz.Dispose()
FileSystem.Rename(Filename, originalFile)
End Sub
Private Function enumerateCheckboxes(ByVal path As String)
originalFile = path
Dim fName As String
For Each Control In Me.Controls
If (TypeOf Control Is CheckBox AndAlso DirectCast(Control, CheckBox).Checked) Then
fName += CStr(Control.Name) + "_"
End If
Next
fName = path + fName.Substring(0, fName.Length - 1) + ".pdf"
Return fName
End Function
End Class

How do I get the file name only, assign it to a variable and use later?

I have the following code:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
Dim saveFileName As String = ""
saveFileDialog1.Filter = "txt files (*.txt)|*.txt"
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
myStream = saveFileDialog1.OpenFile()
saveFileDialog1.FileName = saveFileName
Using sw As StreamWriter = New StreamWriter(myStream)
' Add some text to the file.
sw.WriteLine(DateTime.Now + " - " + saveFileName) ' Date and File title header
sw.WriteLine("-------------------")
' Arbitrary objects can also be written to the file.
sw.Write("The date is: ")
sw.WriteLine(DateTime.Now)
sw.Close()
End Using
If (myStream IsNot Nothing) Then
' Code to write the stream goes here.
myStream.Close()
End If
End If
End Sub
The variable is saveFileName, however when I use the saveFileDialog1.FileName as it, it is empty or provides the full path to the file, how do I only get the name? (such as test.txt)
Use Path.GetFileName
saveFileName = Path.GetFileName(saveFileDialog1.FileName)
DIM fileName = IO.Path.GetFileName(SavefileDialog.FileName)

How to add else statement into downloading code?

I'm making a file downloader and I want it to download files to either my selected directoy or default directory.
Downloading code is here:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Button1.Enabled = False
Button1.Text = "Updating..."
WebBrowser1.Visible = True
Dim uri As System.Uri = New System.Uri("http://199.91.154.170/e9f6poiwfocg/pei02c8727sa720/Ultra+v08.zip")
Dim webclient As System.Net.WebClient = New System.Net.WebClient()
Dim path As String =
If apppath = Nothing then
New String(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "test\\Test.zip"))
Else New String
(apppath)
End if
Dim fileInfo As System.IO.FileInfo = New System.IO.FileInfo(path)
If Not System.IO.Directory.Exists(fileInfo.Directory.FullName) Then
System.IO.Directory.CreateDirectory(fileInfo.Directory.FullName)
End If
AddHandler webclient.DownloadFileCompleted, AddressOf webclient_DownloadDataCompleted
webclient.DownloadFileAsync(uri, path)
End Sub
Private Sub
And user selected path apppath is defined here:
If apppath = "" Then
Dim dialog As New FolderBrowserDialog()
dialog.RootFolder = Environment.SpecialFolder.Desktop
dialog.SelectedPath = Path.Combine(Environment.GetFolderPath( _
Environment.SpecialFolder.ApplicationData))
dialog.Description = "Select directory where to install the files"
If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
apppath = dialog.SelectedPath
End If
My.Computer.FileSystem.WriteAllText(apppath & " apppath.txt", apppath, False)
End If
How to fix Dim path As String else statement?
Thanks in advance!
If I am understanding your question correctly then I believe there is a simple solution, which is this:
Dim path As String
If apppath = Nothing then
path = New String(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "test\Test.zip"))
Else New String
path = apppath
End if
If I have not understood your requirements correctly, then please provide more information.

How to open a .txt file and display it in a text box using Visual Basic 2008 Express Edition

I am using Visual Basic 2008 Express Edition, and this is very new to me. I have a browse button, and I added code in such a way that a file is browsed and its path is displayed in a label box when I click the browse button.
Similarly I want the content of the file I select to be displayed in text box. I use the following code:
Imports System.IO.StreamReader
Dim oReader As StreamReader
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
OpenFileDialog1.Multiselect = False
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
oReader = New StreamReader(OpenFileDialog1.FileName, True)
RichTextBox1.Text = oReader.ReadToEnd
End If
But I got syntax a error for the Imports line and StreamReader as undeclared. How can I fix this problem?
Your import statement should be at the very top of the file, outside of a Sub or Function, and your oReader declaration should be at least inside the class, or inside a method.
Additionally, your import is not right. "Imports System.IO.StreamReader" should be "Imports System.IO", otherwise you will only have access to the classes declared within StreamReader (if there are any). What you really want is to import the System.IO namespace so that you have access to the types declared in that namespace.
Imports System.IO
Public Class MyForm
' ... Whatever code you have for your form
Public Sub OpenFile()
Dim oReader As StreamReader
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
OpenFileDialog1.Multiselect = False
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
oReader = New StreamReader(OpenFileDialog1.FileName, True)
RichTextBox1.Text = oReader.ReadToEnd
End If
End Sub
End Class
You should be importing System.IO namespace.
And see these changes in the code:
Dim oReader As StreamReader
openFileDialog1.CheckFileExists = True
openFileDialog1.CheckPathExists = True
openFileDialog1.DefaultExt = "txt"
openFileDialog1.FileName = ""
openFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
openFileDialog1.Multiselect = False
If openFileDialog1.ShowDialog() = DialogResult.OK Then
oReader = New StreamReader(openFileDialog1.FileName, True)
richTextBox1.Text = oReader.ReadToEnd()
End If
Its very simple use below code that will help you
Open file code
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Me.RichTextBox1.LoadFile(OpenFileDialog1.FileName, RichTextBoxStreamType.PlainText)
End If
Save code
If SaveFileDialog1.ShowDialog = DialogResult.OK Then
RichTextBox1.SaveFile(SaveFileDialog1.FileName, RichTextBoxStreamType.PlainText)
End If
Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
Dim a As String
Dim B As String
Do
a = reader.ReadLine
For i = 0 To a.Length
If a.Substring(i, 1).ToString() = "{" Then
B = B & a.Substring(i)
LBL.Text = B
End If
'Iam Juman Mandra
Next
Loop Until a Is Nothing
reader.Close()

How to specify path using open file dialog in vb.net?

In the first start of my application I need to specify a path to save some files to it. But in the open file dialogue it seems like that I have to select a file to open. How can I just specify a folder without oppening a file
like C:\config\
Here is my code
If apppath = "" Then
Dim fd As OpenFileDialog = New OpenFileDialog()
fd.Title = "Select Application Configeration Files Path"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True
If fd.ShowDialog() = DialogResult.OK Then
apppath = fd.FileName
End If
My.Computer.FileSystem.WriteAllText(apppath & "apppath.txt", apppath, False)
End If
I need to select a file in order for it to work, but I just want to select a folder. So what's the solution?
You want to use the FolderBrowserDialog class instead of the OpenFileDialog class. You can find more information about it here:
http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog(v=vs.110).aspx
For instance, you could do this:
If apppath = "" Then
Dim dialog As New FolderBrowserDialog()
dialog.RootFolder = Environment.SpecialFolder.Desktop
dialog.SelectedPath = "C:\"
dialog.Description = "Select Application Configeration Files Path"
If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
apppath = dialog.SelectedPath
End If
My.Computer.FileSystem.WriteAllText(apppath & "apppath.txt", apppath, False)
End If
If I understand correctly, you want to let the user choose a folder. If that is the case, then you want to use FolderBrowserDialog instead of OpenFileDialog.
Dim filedialog As New OpenFileDialog
filedialog.IntialDirectory = Application.StartupPath
filedialog.ShowDialog()
Or you can simply just make it less lines and very simple.
link: http://i.imgur.com/bMq0HNz.png
Start your dialog with a click:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FolderBrowserDialog1.ShowDialog()
End Sub
Add if you want to show the actual path that you choose from your dialog
Private Sub FolderBrowserDialog1_Disposed(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = FolderBrowserDialog1.SelectedPath.ToString
End Sub
Use To:
Dim openFD As New OpenFileDialog()
Dim Directory As string = openFD.FileName
Try this
Private Sub BtnOpen_Click(sender As Object, e As EventArgs) Handles BtnOpen.Click
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "x_pathfileforsend"
openFileDialog1.Filter = "txt files (*.txt)|*.txt|*.zip|*.rar|*.ico|*.exe|*.png|*.bmp|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 5
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = DialogResult.OK Then
txtpath.Text = openFileDialog1.FileName
End If
openFileDialog1.Dispose()
End Sub