Hi i cant seem to get mkdir to create a folder which isnt read only, this is causing alot of problems in my code because i am unable to write files to the directory i have created. thanks for any help. this is my code below:
Else
MessageBox.Show("Please set a Root Path for your ****")
RootFBD.ShowDialog()
TextBox1.Text = RootFBD.SelectedPath
My.Computer.FileSystem.CreateDirectory("C:\****-Tools\config\root.txt")
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim f2 As New FileIOPermission(FileIOPermissionAccess.Read, TextBox1.Text)
f2.AddPathList(FileIOPermissionAccess.Write Or FileIOPermissionAccess.Read, TextBox1.Text)
Dim rootSave As System.IO.StreamWriter
rootSave = My.Computer.FileSystem.OpenTextFileWriter("C:\****-Tools\config\root.txt", True)
rootSave.WriteLine(TextBox1.Text)
Me.Hide()
MainTool.Show()
End Sub
End Class
Thanks again josh
You're misunderstanding the problem; this isn't a permission issue.
Rather, you're leaving the file open, which prevents other processes from writing to ir.
You just need to Close() your StreamWriter.
Or, you can just call File.AppendText, which will avoid the issue.
You are creating the directory with the file name. Try this:
My.Computer.FileSystem.CreateDirectory("C:\****-Tools\config")
Related
I am posting here to ask you for help, thank you first of all for reading my message and being able to help me. :)
So here's the problem, I have a little program that I'm creating, in this one, I integrated a button that normally allows to download a tool to run it.
However the link of the file does not point directly in .exe it is a link like this one :
mydomain.com/file/file48.php
The problem is that I manage to get the file, but this one is named file48.php and gets the extension of a php file, what I would like is to get the original name of the downloaded .exe file in order to be able to execute it within my application.
Here is the current code I'm using :
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim client As New WebClient
AddHandler client.DownloadFileCompleted, AddressOf client_DownloadFileCompleted
client.DownloadFileAsync(New Uri("https ://mydomain.com/files/index.php"), fileName, filename)
End Sub
Private Sub client_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
Dim client = DirectCast(sender, WebClient)
client.Dispose()
Dim filename As String = CType(e.UserState, String)
End Sub
Thanks a lot for your help, I've been searching for hours without much success...
I have code which asks the user for a folder path and then copies an MDB file to that folder for back-up. However, the MDB is being copied from the wrong folder. How can I fix it so that it uses the right data folder when backing-up and restoring the MDB?
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Try
Dim fbd As New FolderBrowserDialog
If fbd.ShowDialog() = vbOK Then
System.IO.File.Copy("MHC.mdb", fbd.SelectedPath & "\MHC.mdb")
MsgBox("Done")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnRestore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRestore.Click
Try
Dim fbd As New FolderBrowserDialog
If fbd.ShowDialog() = vbOK Then
File.Delete("MHC.mdb")
System.IO.File.Copy(fbd.SelectedPath & "\MHC.mdb", "MHC.mdb")
MsgBox("Done")
Application.Restart()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Yes I want to know the DataDirectory path.
The |DataDirectory| path placeholder as used in a connection string similar to this example:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Northwind.MDB
may be retrieved using code similar to this:
Dim objDataDir As Object = AppDomain.CurrentDomain.GetData("DataDirectory")
Dim dataDirectory As String = TryCast(objDataDir, String)
Beware that the above code can return Nothing (null) for dataDirectory. The only scenario that I know of that sets a "DataDirectory" is an application published using ClickOnce.
If dataDirectory is null, then you probably want to assign the Application.StartupPath property to it.
I do not know of any official documentation that states this is the proper procedure, but the code is based off of the ExpandDataDirectory method.
There is also a non-publicly scoped DataDirectory Property on the AppDomain.CurrentDomain.ActivationContext object, but you would need to use reflection to retrieve that property.
Note that if you want to use the |DataDirectory| placeholder, but point it to a path of your choice, you can use:
AppDomain.CurrentDomain.SetData("DataDirectory", "your path here")
I am new to Visual Basic.NET and I am just playing around with it. I have a book that tells me how to read from a file but not how to write to the file with a button click. All I have is a button and a textbox named fullNameBox. When I click the button it gives me an unhandled exception error. Here is my code:
Public Class Form1
Sub outputFile()
Dim oWrite As System.IO.StreamWriter
oWrite = System.IO.File.CreateText("C:\sample.txt")
oWrite.WriteLine(fullNameBox.Text)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
outputFile()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
Have you tried stepping through your application to see where the error is? With a quick glance, it looks like you might need to use System.IO.File on the fourth line (oWrite = IO.File...) instead of just IO, but I haven't tried to run it.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SaveFileDialog1.FileName = ""
SaveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
SaveFileDialog1.ShowDialog()
If SaveFileDialog1.FileName.Trim.Length <> 0 Then
Dim fs As New FileStream(SaveFileDialog1.FileName.Trim, FileMode.Create)
Dim sr As New StreamWriter(fs)
sr.Write(TextBox1.Text)
fs.Flush()
sr.Close()
fs.Close()
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName.Trim.Length <> 0 Then
Dim fs As New FileStream(OpenFileDialog1.FileName.Trim, FileMode.Open)
Dim sw As New StreamReader(fs)
TextBox1.Text = sw.ReadToEnd
fs.Flush()
sw.Close()
fs.Close()
End If
End Sub
End Class
this is a complete functional program if you want, you just need to drag drop a textbox, openfiledialog, and a savefiledialog.
feel free to play around with the code.
enjoy
by the way, the problem in your code is that you "must" close filestream when your done using it, doing so will release any resource such as sockets and file handles.
The .net framework is a very powerful framework. In the same way (however) it has easy and convenient methods for simple tasks. Most individuals tend to complicate things in order to display knowledge. But less code = less processing = faster and more efficient application (sometimes) so the large above method may not be suitable. Along with that, the above mentioned method would be better off written as a sub or if returning something then a function.
My.Computer.FileSystem.WriteAllText("File As String", "TextAsString", Append as Boolean)
A general Example would be
My.Computer.FileSystem.WriteAllText("C:\text.text", "this is what I would like to add", False)
this is what I would like to add
can be changed to the current text of a field as well.
so a more specific example would be
My.Computer.FileSystem.WriteAllText("C:\text.text", fullNameBox.text, True)
If you would like to understand the append part of the code
By setting append = true you are allowing your application to write the text at the end of file, leaving the rest of the text already in the file intact.
By setting append = false you will be removing and replacing all the text in the existing file with the new text
If you don't feel like writing that part of the code (though it is small) you could create a sub to handle it, however that method would be slightly different, just for etiquette. functionality would remain similar. (Using StreamWriter)
Private Sub WriteText()
Dim objWriter As New System.IO.StreamWriter("file.txt", append as boolean)
objWriter.WriteLine(textboxname.Text)
objWriter.Close()
End Sub
The Specific Example would be
Private Sub WriteText()
Dim objWriter As New System.IO.StreamWriter("file.txt", False)
objWriter.WriteLine(fullnamebox.Text)
objWriter.Close()
End Sub
then under the button_click event call:
writetext()
You can take this a step further as well. If you would like to create a more advabced Sub to handle any textbox and file.
Lets say you plan on having multiple separate files and multiple fields for each file (though there is a MUCH cleaner more elegant method) you could create a function. {i'll explain the concept behind the function as thoroughly as possible for this example}
below is a more advanced sub demonstration for your above request
Private Sub WriteText(Filename As String, app As Boolean, text As String)
Dim objWriter As New System.IO.StreamWriter(Filename, app)
objWriter.WriteLine(text)
objWriter.Close()
End Sub
What this does is allows us to (on the same form - if you need it global we can discuss that another time, it's not much more complex at all) call the function and input the information as needed.
Sub Use -> General Sample
WriteText(Filename As String, app As Boolean)
Sub Use -> Specific Sample
WriteText("C:\text.txt, False, fullnamebox.text)
But the best part about this method is you can change that to be anything as you need it.
Let's say you have Two Buttons* and **Two Boxes you can have the button_event for the first button trigger the above code and the second button trigger a different code.
Example
WriteText("C:\text2.txt, False, halfnamebox.text)
The best part about creating your own functions and subs are Control I won't get into it, because it will be off topic, but you could check to be sure the textbox has text first before writing the file. This will protect the files integrity.
Hope this helps!
Richard Sites.
I have looked everywhere and cannot find a version that works. The ones I found are all either outdated or have errors.
I have something that is working for the most part, but I'm having some trouble with restricted-access folders.
The code I'm using is as follows:
Imports System.IO
Public Class frmMain
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each drive In DriveInfo.GetDrives
Dim i As Integer = TreeView1.Nodes.Count
TreeView1.Nodes.Add(drive.ToString)
If drive.IsReady Then
PopulateTree(drive.ToString, TreeView1.Nodes(i))
End If
Next
End Sub
Private Sub PopulateTree(ByVal sDir As String, ByVal node As TreeNode)
Dim directory As New DirectoryInfo(sDir)
Try
For Each d As DirectoryInfo In directory.GetDirectories
Dim t As New TreeNode(d.Name)
PopulateTree(d.FullName, t)
node.Nodes.Add(t)
Next
Catch excpt As UnauthorizedAccessException
Debug.WriteLine(excpt.Message)
End Try
End Sub
End Class
For testing purposes I replaced this section...
If drive.IsReady Then
PopulateTree(drive.ToString, TreeView1.Nodes(i))
End If
...with this...
If drive.toString = "L:\"
PopulateTree(drive.ToString, TreeView1.Nodes(i))
End If
...and it worked fine for that drive. The L:\ is a removable USB drive by the way.
However, with the original code I get debug errors on some folders because they are access-restricted. Is there any way to ignore those particular folders and show the rest?
Yes, you need to tighten the scope of your try catch block. You are catching the error too far away from where it occurs. Try this:
Private Sub PopulateTree(ByVal sDir As String, ByVal node As TreeNode)
Dim directory As New DirectoryInfo(sDir)
For Each d As DirectoryInfo In directory.GetDirectories
Dim t As New TreeNode(d.Name)
Try
PopulateTree(d.FullName, t)
node.Nodes.Add(t)
Catch excpt As UnauthorizedAccessException
Debug.WriteLine(excpt.Message)
EndTry
Next
End Sub
How can I use a .exe file in my resources folder? I want to copy the file in the resource folder to another folder.
tried this
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If (Directory.Exists("Files")) Then
Else
End If
Directory.CreateDirectory("Files")
Dim FileToCopy As String
Dim NewCopy As String
FileToCopy = My.Resources.THEFILEIWANT <- only this part doesn't work
NewCopy = "Files\THEFILEIWANT.exe"
If System.IO.File.Exists(FileToCopy) = True Then
System.IO.File.Copy(FileToCopy, NewCopy)
End If
End Sub
This is needed so when ther file doesn't exists the file gets created/copied.
Does anyone knows how I can call the file from the resource folder?
Tried this ` Dim writePermission As FileIOPermission
writePermission = New FileIOPermission(FileIOPermissionAccess.Write)
If (SecurityManager.IsGranted(writePermission)) Then
My.Computer.FileSystem.WriteAllBytes("Files", My.Resources.unscrambler, False)
End If`
But I'm getting a invalid permission error.
I am still a beginner but I could suggest using a packer, such as the one included with CodePlex's Confuser. It packs multiple assemblies into one (as do all packers), and obviously, Confuser offers obfuscation, and is Free.
*One warning!* Packers have been known to raise alerts in Anti-virus software, so check your app with different AV software.
Hope this info is useful. :)