I have a code that copy a folder to another location through textboxes. Textbox1 where the user can specify which folder to copy and textbox2 that the user can browse for a destination folder.
If Textbox1 is the path to "My documents" an error occur saying:
Access to path C:\Users\%USERNAME%\Documents\My Music is denied.
"My Music" is a hidden folder in "My document" that is checked as "hide protected operating system files" by windows 7. I am using Visual Studio 2005 and new in VB.net, can anybody take a look at this code and tell me a way to exclude folders to copy?
Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
Dim fs As Object = CreateObject("Scripting.FileSystemObject")
Dim sFolderpath As String = TextBox1.Text
Dim sourceFolderName As String = System.IO.Path.GetFileName(sFolderpath)
Dim strDate As String = DateTime.Now.ToString("yyyy-MM-dd")
Dim dFolderpath As String = System.IO.Path.Combine(TextBox6.Text, strDate)
fs.createfolder(dFolderpath)
dFolderpath = System.IO.Path.Combine(dFolderpath, sourceFolderName)
fs.createfolder(dFolderpath)
fs.copyfolder(sFolderpath, dFolderpath)
End Sub
I'd suggest splitting the problem into 4 subs. Firstly two subs to allow users to select a folder they desire for source and destination. The a button click event that starts the copying and finally a sub that actually handles the copying.
Try this on for size:
Dim CopyFromPath As String
Dim CopyToPath As String
Private Sub TextBox1_MouseClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.MouseClick
Dim fldbroser1 As New FolderBrowserDialog
fldbroser1.RootFolder = Environment.SpecialFolder.MyMusic
fldbroser1.ShowDialog()
CopyFromPath = fldbroser1.SelectedPath
End Sub
Private Sub TextBox2_MouseClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.MouseClick
Dim fldbroser1 As New FolderBrowserDialog
fldbroser1.RootFolder = Environment.SpecialFolder.MyComputer
fldbroser1.ShowDialog()
CopyToPath = fldbroser1.SelectedPath
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
CopyAllFiles(CopyFromPath, CopyToPath)
End Sub
Private Sub CopyAllFiles(ByVal CopyFromPath As String, ByVal CopyToPath As String)
If Not Directory.Exists(CopyToPath) Then
Directory.CreateDirectory(CopyToPath)
End If
For Each filee As String In Directory.GetFiles(Path.GetDirectoryName(CopyFromPath))
Dim dest As String = Path.Combine(CopyToPath, Path.GetFileName(filee))
File.Copy(filee, dest)
Next
For Each folder As String In Directory.GetDirectories(Path.GetDirectoryName(CopyFromPath))
Dim dest As String = Path.Combine(CopyToPath, Path.GetFileName(folder))
CopyAllFiles(folder, dest)
Next
End Sub
You will need to import System.IO for this to work. Fell free to ask any questions if you have trouble with the code. Good luck learning VB, it can be annoying at times but it's pretty useful.
Related
I'm kind of confused on how to do this. What I want to do is when I click Button1, my program will open a folder in Explorer, and the second button will open a file as a text file.
Here's my code:
Button 1
Process.Start("explorer.exe", Application.ExecutablePath + "\mvram.biz")
Button 2
Process.Start("Notepad.Exe", "README.txt")
My problem is everytime I click the button it will open My Documents. It must open the APPpath+Specific Folder.
EDIT:
Public Class Form1
Private Sub ExcisionButtonDefault5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcisionButtonDefault5.Click
Me.Close()
End Sub
Private Sub ExcisionButtonDefault1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcisionButtonDefault1.Click
Dim path As String = System.IO.Path.GetDirectoryName(Application.ExecutablePath) & "\mvram.biz\"
Process.Start("explorer.exe", path)
End Sub
Private Sub ExcisionButtonDefault2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcisionButtonDefault2.Click
Process.Start("explorer.exe", Application.StartupPath & "\Documents")
End Sub
Private Sub ExcisionButtonDefault3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcisionButtonDefault3.Click
Process.Start("Notepad.Exe", "/select," & "README.txt")
End Sub
Private Sub ExcisionButtonDefault4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcisionButtonDefault4.Click
Process.Start("explorer.exe", System.Windows.Forms.Application.StartupPath + "\Presentation")
End Sub
Private Sub ExcisionButtonDefault6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExcisionButtonDefault6.Click
System.Diagnostics.Process.Start("http://www.mvram.biz")
End Sub
End Class
The reason why it opens a random location is because you are intending to execute a wrong path (whole app path + other app). You have to choose the directory. Try this code:
Dim path As String = System.IO.Path.GetDirectoryName(Application.ExecutablePath) & "\mvram.biz"
Process.Start("explorer.exe", path)
Other option:
Dim path As String = Environment.CurrentDirectory & "\mvram.biz"
I personally prefer to use absolute paths rather than relative ones (just the name of the file when referring to the same directory).
To open a specific folder in FileExplorer, you can try passing this argument:
Dim x as string = "FolderPath"
Process.Start("explorer.exe", "/root,x")
Or you could pass the argument "/select,x", which will open File Explorer with the folder selected, but not opened. This article may be helpful. Or you can just have the file address, like you tried above, and it will open to the correct location.
And then to open a txt file, all you need to do is:
Process.Start("FileAddress")
This will open the file in its default editor.
HTH
I am having trouble converting this code into allowing me to drop files into my application and my application create a message box saying its md5 hash code. Currently, I have the code to give the directory of the file I dropped in.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.AllowDrop = True
End Sub
Private Sub Form1_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
For Each path In files
MsgBox(path)
Next
End Sub
Private Sub Form1_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
End Class
Seems like you have most of the code you need, only needs a function to calculate the md5, and then you can plug that into your message box:
MsgBox(ComputeMD5Hash(path))
Here is the function, taken mostly from this Microsoft Support Article
Private Function ComputeMD5Hash(ByVal path As String) As String
Dim tmpSource() As Byte
Dim tmpHash() As Byte
'Create a byte array from source data.
tmpSource = My.Computer.FileSystem.ReadAllBytes(path)
'Compute hash based on source data.
tmpHash = New Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(tmpSource)
Dim i As Integer
Dim sOutput As New System.Text.StringBuilder(tmpHash.Length)
For i = 0 To tmpHash.Length - 1
sOutput.Append(tmpHash(i).ToString("X2"))
Next
Return sOutput.ToString()
End Function
In-case you want to drop a directory and get all the hashes of the files inside you first need to check if you're dealing with a file or a folder, if its a folder you loop over all the files inside and call the function for each one, which would make your DragDrop event handler look something like this, and have the added benefit both files and folders can be taken care of.
Private Sub Form1_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
For Each path In files
If IO.File.GetAttributes(path) = FileAttribute.Directory Then
'Dealing with a Directory
Dim di As New IO.DirectoryInfo(path)
Dim fiArr As IO.FileInfo() = di.GetFiles()
Dim fri As IO.FileInfo
For Each fri In fiArr
MessageBox.Show(fri.FullName & " " & ComputeMD5Hash(fri.FullName))
Next fri
Else
'Dealing with a File
MessageBox.Show(path & " " & ComputeMD5Hash(path))
End If
Next
End Sub
I was trying to display data from file in a list saved on the hard drive by clicking on a button, however I'm not sure on haw to do it properly:
Private Sub btnListRecipes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListRecipes.Click
Dim TextLine As String
If System.IO.File.Exists(Filename) = True Then
Dim RecipeReader As New System.IO.StreamReader(Filename)
Do While RecipeReader.Peek() <> -1
TextLine = TextLine & RecipeReader.ReadLine() & vbNewLine
Loop
lstRecipes.Text = TextLine.Text
Else
MsgBox("File Does Not Exist")
End If
End Sub
I would be really grateful for assistance :D
Private Sub btnListRecipes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListRecipes.Click
Try
lstRecipes.AddRange(File.ReadAllLines(FileName))
Catch
MsgBox("Unable to read file")
End Try
End Sub
Use:
lstRecipes.Items.Add(TextLine.Text)
More specifically before it jumps to the next item in the list, so this would go right after your assignment of TextLine.
you can do this:
Imports System
Imports System.IO
Public Class Form1
Public Shared listTXT, listOfTxt, listOfTxtFile As New List(Of String)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim path As String = "C:\myDirectory\"
Dim parentinfo As New DirectoryInfo(path)
' Store Text file name in a list
For Each txtFile As FileSystemInfo In parentinfo.GetFileSystemInfos()
listTXT.Add(txtFile.Name)
Next
' Store Path of Text file in a list
For noOfTxtFile = 0 To listTXT.Count - 1
Dim pathOfFile As String = path & listTXT(noOfTxtFile)
listOfTxtFile.Add(pathOfFile)
Dim obj As System.IO.StreamReader
obj = System.IO.File.OpenText(pathOfFile)
While Not obj.EndOfStream
listOfTxt.Add(obj.ReadLine)
End While
Next
Dim lineOfTxt As Integer
Dim txt As String
For lineOfTxt = 0 To listOfTxt.Count - 1
txt = listOfTxt(lineOfTxt)
ListBox1.Items.Add(txt)
Next
End Sub
End Class
It works perfectly in debug mode but it gives me 'The process cannot access the file because it is being used by another process' unhandled exception error when I run the built one and press the Save button(It loads but not saves after that).
Any advice, please.
Imports System.IO
Public Class DL1
Function DirExists(ByVal DirName As String) As Boolean
On Error GoTo ErrorHandler
DirExists = GetAttr(DirName) And vbDirectory
ErrorHandler:
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub LoadGlink_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadGlink.Click
GlinkList.Items.Clear()
Dim fileReader As System.IO.StreamReader
fileReader = _
My.Computer.FileSystem.OpenTextFileReader("c:\Source\DL1\Glink.txt")
Dim mystring() As String = fileReader.ReadToEnd.Split(vbNewLine)
GlinkList.Items.AddRange(mystring)
fileReader.Close()
Me.Controls("Glinklist").Focus()
End Sub
Private Sub linktochrome_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles linktochrome.Click
If GlinkList.SelectedItem IsNot Nothing Then
' selected item is sglink
Dim sglink = GlinkList.SelectedItem.ToString
Process.Start("C:\Users\1\AppData\Local\Google\Chrome\Application\chrome.exe", sglink)
End If
Me.Controls("Glinklist").Focus()
End Sub
Private Sub movetofol_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles movetofol.Click
Dim strDir As String
strDir = "C:\Users\1\Downloads\Glink\" & "\" & SFoltext.Text
If DirExists(Trim(strDir)) = False Then
MkDir(Trim(strDir))
End If
For Each f As String In Sresult1.Items
Dim f_name As String = Path.GetFileName(f)
My.Computer.FileSystem.MoveFile(f, strDir & "\" & f_name)
Next
Sresult1.Items.Clear()
GlinkList.Items.Remove(GlinkList.SelectedItem)
End Sub
Private Sub ChecKDL_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChecKDL.Click
Sresult1.Items.Clear()
Dim fileList As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
fileList = My.Computer.FileSystem.GetFiles("C:\Users\1\Downloads\")
For Each foundFile As String In fileList
Sresult1.Items.Add(foundFile)
Next
End Sub
Private Sub Bsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Bsave.Click
Dim i As Integer
'Saves Glinklist
Dim path As String = System.IO.Path.Combine("c:\Source\DL1\", "Glink.txt")
Using fs As New System.IO.FileStream(path, IO.FileMode.Create)
Using w As IO.StreamWriter = New IO.StreamWriter(fs)
For i = 0 To GlinkList.Items.Count - 1
w.WriteLine(GlinkList.Items.Item(i))
Next
w.Close()
End Using
End Using
End Sub
Private Sub RMselec_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RMselec.Click
GlinkList.Items.Remove(GlinkList.SelectedItem)
Me.Controls("Glinklist").Focus()
End Sub
End Class
Not sure it this could be the answer, but I will post here because I can better format the code.
Let me know if this changes anything
Change your reading function to
Using fileReader = _
My.Computer.FileSystem.OpenTextFileReader("c:\Source\DL1\Glink.txt")
Dim mystring() = fileReader.ReadToEnd.Split(vbNewLine)
GlinkList.Items.AddRange(mystring)
End Using
Or simply
Dim mystring() = File.ReadAllLines()
GlinkList.Items.AddRange(mystring)
Usually this means a permission issue. Try running Visual Studio as admin to eliminate that possibility.
I have a checkedlistbox and I want to drag and drop only image extensions and not text files.
so how do I get it done.
I am able to drag and drop all file formats but I need only image files.
Here is my code:
Private Sub CheckedListBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles CheckedListBox1.DragDrop
Dim Files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
For Each FileName As String In Files
CheckedListBox1.Items.Add(FileName, CheckState.Checked)
Thumbcontrol1.AddThumbnail(FileName)
Next
End Sub
Private Sub CheckedListBox1_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles CheckedListBox1.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
Just check each file name's extension.
Private Shared ReadOnly SupportedExtensions As String() = {".jpg", ".jpeg", ".gif"}
Private Sub CheckedListBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles CheckedListBox1.DragDrop
Dim Files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
For Each FileName As String In Files
Dim Extension As String = Path.GetExtension(FileName).ToLower
If Array.IndexOf(SupportedExtensions, Extension) <> -1 Then
CheckedListBox1.Items.Add(FileName, CheckState.Checked)
Thumbcontrol1.AddThumbnail(FileName)
End If
Next
End Sub
You may want to add similar code to the DragEnter method to show DragDropEffects.None if there are no picture files in the dragged file list.
Something like this (you'll need to add in more file extensions):
Dim Files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
For Each FileName As String In Files
If FileName.Contains(".jpg") Or FileName.Contains(".bmp") Then
CheckedListBox1.Items.Add(FileName, CheckState.Checked)
Thumbcontrol1.AddThumbnail(FileName)
End If
Next
You will also need to account for the case of the filenames.