如何将多个文件从checkedListBox复制到文件夹VB

如何将多个文件从checkedListBox复制到文件夹VB

本文介绍了如何将多个文件从checkedListBox复制到文件夹VB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我该怎么做?这就是我要做的事情: 屏幕上显示我想要实现的内容 这是我创建的控件:Button1浏览...到文件,我正在使用OpenFileDialog选择文件并将它们添加到CheckListBox1中,TextBox1包含文件复制到的路径,例如D:\ temp,Checkbox1,Checkbox2,Checkbox3是在D:\ temp \ pdder1下选中时创建的文件夹,如果没有选中CheckBox则没有文件夹且没有文件Button2复制文件当创建单击的文件夹时,文件根据Checkbox1,Checkbox2,Checkbox3复制到TextBox1的路径,如果他们选中的话。 这是我的代码: 私人 Sub Button1_Click(发件人作为 对象, e As EventArgs)句柄 Button1.Click Dim browseFiles As 新 OpenFileDialog browseFiles.Title = 选择要复制的文件 browseFiles.Filter = 所有文件(*。*)| *。* ' 允许在打开的文件对话框中进行多选 browseFiles.Multiselect = True Dim result As DialogResult = browseFiles.ShowDialog () 如果 不 result = Windows.Forms.DialogResult.Cancel 然后 ' 这里是它的文件名用s返回文件名数组 Dim names() As String = browseFiles.FileNames 对于 每个 name As String 在 name Dim fileName As String = System.IO.Path.GetFileName(name) CheckedListBox1.Items.Add(fileName) Next 结束 如果 结束 Sub 私有 Sub Button2_Click (发件人作为 对象,e 作为 EventArgs )句柄 Button2.Click Dim txt As String txt = TextBox1.Text 如果 CheckBox1.CheckState = 1 然后 My.Computer.FileSystem.CreateDirectory( & txt& \ File1) MessageBox.Show( Folder1已成功创建,单击确定) 结束 如果 如果 CheckBox2.CheckState = 1 然后 My.Computer.FileSystem.CreateDirectory( & txt& \ File2) MessageBox.Show( Folder2已成功创建,单击确定) 结束 如果 如果 CheckBox3 .CheckState = 1 然后 My.Computer.FileSystem.CreateDirectory( & txt& \ File3) MessageBox.Show( Folder3已成功创建,单击确定) 结束 如果 如果 CheckBox4.CheckState = 1 然后 My.Computer.FileSystem.CreateDirectory( & txt& \ File4) MessageBox.Show( Folder4已成功创建,单击确定) 结束 如果 结束 Sub 解方案 一开始,你使用了错误的控制,如果你想在基于文件夹的路径上的目录中的所有文件的列表。 (除非你只想要专门选择这些文件)。 当你最好使用OpenFolderDialog时,你正在使用OpenFileDialog。如果您想要选择手动添加哪些文件,我只会使用OpenFileDialog,否则您可以使用递归测量为您完成工作。 只需打开文件夹对话框,即可返回用户选择的文件夹路径。 您可以使用 System.IO.DirectoryInfo 返回目录信息, System.IO.FileInfo 返回文件信息。要返回该目录中文件的列表,您可以使用上面示例中的System.IO.Path. 您不需要这个,因为如果可以选择路径,则路径永远不会为空。 :) 如果不是String.IsNullOrEmpty(txtFolderPath.Text)那么 我用folderdialog改写了它。如果您需要,也很容易将其更改回来。这段代码工作得很好,我已经包含了很多功能,可以让你使用文件路径和文件名,这就是为什么我使用字典的原因。 代码未注释,但如果您有任何疑问,请与我们联系。如果您对此感到满意,请将其标记为解决方案。 #RegionDeclationss Dim FileDetails 作为 新字典( 字符串,字符串) Dim CheckedItem 作为 整数 = 0 Dim CheckedSelected As 字符串 = #End Region #Region子程序 私有 Sub Button1_Cli ck(发件人作为 对象,e 作为 EventArgs)句柄 Button1.Click Dim result As DialogResult = FolderBrowserDialog.ShowDialog() 如果 不 result = Windows.Forms.DialogResult.Cancel 然后 GetListOfFiles(Currentlocation:= FolderBrowserDialog.SelectedPath,NewLocation:= FolderBrowserDialog。 SelectedPath& \& folder,完成:= False) 结束 如果 结束 Sub 私有 Sub Button2_Click(发件人) 作为 对象,e 作为 EventArgs)句柄 Button2.Click 对于 我 .CheckedItem = 0 CheckedListBox1.CheckedItems.Count - 1 CheckedSelected = CheckedListBox1.CheckedItems(CheckedItem).ToString If FileDetails.ContainsKey(CheckedSelected)然后 ' 写入密钥值。 Dim zLocation As String = Nothing zLocation = FileDetails.Item(CheckedSelected) Dim 比较 As KeyValuePair( String ,字符串) Dim ComparisonValue As String = Nothing Dim eFileNameOnly 作为 字符串 = Nothing 每个比较在 FileDetails 如果 Comparison.Key = CheckedSelected 那么 ComparisonValue = Comparison.Value& Comparison.Key eFileNameOnly = Comparison.Key FileCopy(iLocation:= zLocation,iNewLocation:= zLocation& folder \,eFile:= ComparisonValue,FileNameOnly:= eFileNameOnly,Done:= False) End 如果 下一步 结束 如果 下一步 结束 Sub #End Region #RegionFunctions 私有 函数 GetListOfFiles( ByVal Curr entlocation 作为 字符串, ByVal NewLocation 作为 字符串, ByRef 完成作为 布尔)作为 字符串 如果 Directory.Exists(NewLocation)= False 然后 My.Computer.FileSystem.CreateDirectory(NewLocation) MessageBox.Show( 文件夹创建成功,单击确定) 结束 如果 对于 每个 eFilename 作为 字符串 在 IO.Directory.GetFiles(Currentlocation) , *,IO.SearchOption.TopDirectoryOnly) Dim iFileName 作为 字符串 = System.IO.Path.GetFileName(eFilename) Dim NewDirNameCut As String = eFilename.Replace(iFileName, ) FileDetails.Add(iFileName,NewDirNameCut) CheckedListBox1.Items.Add(iFileName) Next Done = True 返回完成 结束 功能 私人 功能 FileCopy( ByVal iLocation As 字符串, ByVal iNewLocation 作为 字符串, ByVal eFile 作为 字符串, ByVal FileNameOnly 作为 字符串, ByRef 完成作为 Boolean ) As Boolean If File.Exists(eFile)然后 Dim OldFileToCopy = iLocation& FileNameOnly Dim NewFileToCopy = iNewLocation& FileNameOnly 如果 System.IO.File.Exists(OldFileToCopy)= True 然后 System.IO.File.Copy(OldFileToCopy,NewFileToCopy, True ) 结束 如果 MessageBox.Show( 已复制:& iLocation& FileNameOnly& to& iNewLocation& FileNameOnly) Done = True 返回完成 否则 Done = False 返回完成 结束 如果 结束 功能 #End Region 您好,这是另一种适合您的解决方案。因此,您也可以将此标记为解决方案。如果您有任何疑问,请在我的解决方案下发布您的问题,我会在有空闲时间回复您。 :) 当您要求对复选框位置进行更改时,我提供了两种方法,这些方法在Button2的源代码中有说明。希望它能帮到你。 #RegionMoveFiles Region #RegionDeclations Dim FileDetails As 新字典( 字符串,字符串) Dim CheckedItem 作为 整数 = 0 Dim CheckedSelected 作为 字符串 = ' CBCheckedFolders将用于将两个目录一起添加,如果它们都是选择。 Dim CBCheckedFolders As String = 没有 ' CtrlDict Dictionary将用于从CheckBox Text属性中收集新的文件夹路径,以及一个表示其位置和状态的整数。 Dim CtrlDict As 新字典( 整数,字符串) ' 如果CtrlDict中的值=我们的一个检查状态键已添加 ,则下面的布尔变量为true来自CheckBoxes Checked Changed Event的' 。 Dim CheckA,CheckB,CheckC,CheckD As Boolean Dim FolderBrowserPath As String = Nothing Dim SetLabelPath 作为 字符串 = Dim SetLabelPathCut As 字符串 = 无 #End Region #Region子程序 私有 Sub Form1_Load(sender 作为 对象,e As EventArgs)句柄 MyBase .Load LocationLabel.Visible = False LocationLabel.Text = 位置: 结束 Sub 私有 Sub CB1FolderA_CheckedChanged(sender As Object ,e As EventArgs)句柄 CB1FolderA.CheckedChanged 如果 我 .CB1FolderA.CheckState = CheckState.Checked AndAlso FolderBrowserPath IsNot Nothing 然后 CtrlDict .Add( 1 ,CB1FolderA.Text& \) LocationLabel.Visible = True 如果 不 SetLabelPath.Contains(CB1FolderA.Text)然后 SetLabelPath = SetLabelPath + \ + CB1FolderA.Text LocationLabel.Text = 位置:& FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath 结束 如果 ElseIf Me .CB1FolderA.CheckState = CheckState.Unchecked AndAlso FolderBrowserPath IsNot Nothing 然后 CtrlDict.Remove( 1 ) LocationLabel.Visible = True 如果 SetLabelPath.Contains(CB1FolderA.Text)那么 SetLabelPathCut = SetLabelPath.Replace( \& CB1FolderA.Text, ) SetLabelPath = SetLabelPathCut LocationLabel.Text = 位置:& ; FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath 结束 如果 Else MsgBox( 浏览a文件夹优先。) 结束 如果 结束 Sub 私人 Sub CB2FolderB_CheckedChanged(发件人作为 对象,e As EventArgs)句柄 CB2FolderB.CheckedChanged 如果 我 .CB2FolderB.CheckState = CheckState.Checked 然后 CtrlDict.Add( 2 ,CB2FolderB.Text& \) LocationLabel.Visible = True SetLabelPath = SetLabelPath + \ + CB2FolderB.Text LocationLabel.Text = 位置:& FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath ElseIf Me .CB2FolderB.CheckState = CheckState .Unchecked AndAlso FolderBrowserPath IsNot Nothing 然后 CtrlDict.Remove( 2 ) LocationLabel.Visible = True 如果 SetLabelPath.Contains(CB2FolderB.Text)那么 SetLabelPathCut = SetLabelPath.Replace( \& CB2FolderB.Text, ) SetLabelPath = SetLabelPathCut LocationLabel.Text = 位置:& FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath 结束 如果 LocationLabel。 Text = 位置:& FolderBrowserPath + SetLabelPath 否则 MsgBox( 首先浏览文件夹。) 结束 如果 结束 Sub 私人 Sub CB3FolderC_CheckedChanged(发件人作为 对象,e As EventArgs)句柄 CB3FolderC.CheckedChanged 如果 Me .CB3FolderC.CheckState = CheckState.Checked AndAlso FolderBrowserPath IsNot Nothing Th en CtrlDict.Add( 3 ,CB3FolderC.Text& \) LocationLabel.Visible = True SetLabelPath = SetLabelPath + \ + CB3FolderC.Text LocationLabel.Text = 位置:& FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath ElseIf Me .CB3FolderC.CheckState = CheckState .Unchecked AndAlso FolderBrowserPath IsNot Nothing 然后 CtrlDict.Remove( 3 ) LocationLabel.Visible = True 如果 SetLabelPath.Contains(CB3FolderC.Text)那么 SetLabelPathCut = SetLabelPath.Replace( \& CB3FolderC.Text, ) SetLabelPath = SetLabelPathCut LocationLabel.Text = 位置:& FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath 结束 如果 LocationLabel。 Text = 位置:& FolderBrowserPath + SetLabelPath 否则 MsgBox( 首先浏览文件夹。) 结束 如果 结束 Sub 私人 Sub CB4FolderD_CheckedChanged(发件人作为 对象,e As EventArgs)句柄 CB4FolderD.CheckedChanged 如果 我 .CB4FolderD.CheckState = CheckState.Checked AndAlso FolderBrowserPath IsNot Nothing Th en CtrlDict.Add( 4 ,CB4FolderD.Text& \) LocationLabel.Visible = True SetLabelPath = SetLabelPath + \ + CB4FolderD.Text LocationLabel.Text = \"Location: \" & FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath ElseIf Me.CB4FolderD.CheckState = CheckState.Unchecked AndAlso FolderBrowserPath IsNot Nothing Then CtrlDict.Remove(4) LocationLabel.Visible = True If SetLabelPath.Contains(CB4FolderD.Text) Then SetLabelPathCut = SetLabelPath.Replace(\"\\" & CB4FolderD.Text, \"\") SetLabelPath = SetLabelPathCut LocationLabel.Text = \"Location: \" & FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath End If LocationLabel.Text = \"Location: \" & FolderBrowserPath + SetLabelPath Else MsgBox(\"Browse a folder first.\") End If End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim result As DialogResult = FolderBrowserDialog.ShowDialog() If Not result = Windows.Forms.DialogResult.Cancel Then FolderBrowserPath = FolderBrowserDialog.SelectedPath GetListOfFiles(Currentlocation:=FolderBrowserDialog.SelectedPath, Done:=False) End If End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click For Me.CheckedItem = 0 To CheckedListBox1.CheckedItems.Count - 1 CheckedSelected = CheckedListBox1.CheckedItems(CheckedItem).ToString If FileDetails.ContainsKey(CheckedSelected) Then ' Write value of the key. Dim zLocation As String = Nothing zLocation = FileDetails.Item(CheckedSelected) Dim Comparison As KeyValuePair(Of String, String) Dim ComparisonValue As String = Nothing Dim eFileNameOnly As String = Nothing For Each Comparison In FileDetails If Comparison.Key = CheckedSelected Then ComparisonValue = Comparison.Value & Comparison.Key eFileNameOnly = Comparison.Key Dim Checked As Boolean If WhatsChecked(Done:=Checked) = True Then CombineChecked(RTCombinePath:=CBCheckedFolders) Dim LabelPathText As String = LocationLabel.Text Dim LabelPathTextCut As String = LabelPathText.Remove(0, 10) '#########################What You Need To Do####################### 'You need to add one additional Label to your form called: LocationLabel 'You need to rename your checkboxes on your form as they are named below: 'CB1FolderA, CB2FolderB, CB3FolderC, CB4FolderD 'Add a OpenFolderDiaLog with the name: OpenFolderDiaLog 'Replace your Button1, and Button2 code with mine. 'If you get stuck, or have questions, feel free to ask me in the comments. '########################How It Works############################### 'Now, this part is important as I've wrote this in a way 'that you have two methods, working differently, and they 'both do the same job. They both do the job differently, 'One of the options is using a Dictionary called: CtrlDict 'It adds the value of a selected checkboxes text property 'to a dictionary.value property. 'We then use the dictionary.key property from the same 'Dictionary (CtrlDict) in a function called: WhatsChecked 'This checkes the dictionary keys against each checked 'checkbox. Thus enabling a Boolean value to True for each 'match found... 'We then use the CombineChecked to those Boolean Values we 'set in the: WhatsChecked function, and this returns the 'enabled checkboxes text property for the checkboxes which 'have a CheckState = to Checked. This gives you a variable 'path: CBCheckedFolders with the Checkboxes text property's 'added to the variable which is then used and passed on to 'the function: FileCopy as you can see in the code from 'button 2. '####################Additional Method############################### 'So what is the commented line below the non-commented 'FileCopy function? That is another method which you can 'also use to pass on to the FileCopy Function, and its a lot 'easier to work with than the dictionary method. '(I added the dictionary method to give you experience and 'to show you alternatives to using other functionality to 'broaden your ability to expand on the use of the code.) 'Anyway, The non-commented out FileCopy method below uses a 'LabelPathTextCut Variable which removed the text: Location 'from the variable named: LabelPathText whcih is = to the 'LocationLabel.Text property, and this gives you an absolute 'path to the OpenFolderDialog and the Checked Checkboxes 'text properties. And this is handled in the CheckedChanged 'EventArgs. The SetLabelPathCut and SetLabelPath variables 'handle the Checkboxes (Checked) Text properties and 'combines them. And lastly; the LocationLabel.Text property 'Is then equal to: 'LocationLabel.Text = \"Location: \" & FolderBrowserPath + SetLabelPath 'then we removed the (Location:) part in the: LabelPathTextCut 'variable where you can pass it on to the FileCopy function. 'Job done, and have fun with it, as it is all fully working, and 'you can choose which method you like best and remove the alternative. 'But If you break it, I won't be fixing it. :) 'Now you can remove whatever functionality you don't like or want. '###############################END################################### FileCopy(iLocation:=zLocation, iNewLocation:=LabelPathTextCut & \"\\", eFile:=ComparisonValue, FileNameOnly:=eFileNameOnly, Done:=False) ' FileCopy(iLocation:=zLocation, iNewLocation:=zLocation & CBCheckedFolders, eFile:=ComparisonValue, FileNameOnly:=eFileNameOnly, Done:=False) End If 'Recently added in updated code. End If Next End If Next End Sub #End Region #Region \"Functions\" Private Function CombineChecked(ByRef RTCombinePath As String) As String 'Recently added in updated code. 'This will reset the RTCombinePath each time this function is run. RTCombinePath = Nothing Dim NonNull As KeyValuePair(Of Integer, String) For Each NonNull In CtrlDict 'Now we will write a new directory structure based on the order of the checkboxes. So from CB1FolderA to CB4FolderD 'Returning each one that was checked. With NonNull If CheckA = True Then 'The If Not statement ensures no duplicate additions are added. If Not CBCheckedFolders = Nothing AndAlso Not CBCheckedFolders.Contains(.Value) Then CBCheckedFolders = CBCheckedFolders + (.Value) ElseIf CBChecked Folders = Nothing Then CBCheckedFolders = (.Value) End If End If If CheckB = True Then If Not CBCheckedFolders = Nothing AndAlso Not CBCheckedFolders.Contains(.Value) Then CBCheckedFolders = CBCheckedFolders + (.Value) ElseIf CBCheckedFolders = Nothing Then CBCheckedFolders = (.Value) End If End If If CheckC = True Then If Not CBCheckedFolders = Nothing AndAlso Not CBCheckedFolders.Contains(.Value) Then CBCheckedFolders = CBCheckedFolders + (.Value) ElseIf CBCheckedFolders = Nothing Then $ b$b CBCheckedFolders = (.Key) End If End If If CheckD = True Then If Not CBCheckedFolders = Nothing AndAlso Not CBCheckedFolders.Contains(.Value) Then CBCheckedFolders = CBCheckedFolders + (.Value) ElseIf CBCheckedFolders = Nothing Then CBCheckedFolders = ( .Value) End If End If End With Next RTCombinePath = CBCheckedFolders Return RTCombinePath End Function Private Function WhatsChecked(ByRef Done As Boolean) As Boolean 'Recently added in updated code. Dim NonNull As KeyValuePair(Of Integer, String) For Each NonNull In CtrlDict 'Add Individual ifs to check each key from the collection against each checkbox. 'Example, if NonNul.Key = a Numbered Integer, We know to enable that boolean: 'CheckA to = True. In this case, 1 , 2 , 3 , and 4 represent the first, second 'third and forth checkbox etc.... If NonNull.Key = 1 = False Then Done = False End If If NonNull.Key = 2 = False Then Done = False End If If NonNull.Key = 3 = False Then Done = False End If If NonNull.Key = 4 = False Then Done = False End If 'Now we will write a new directory structure based on the order of the checkboxes. So from CB1FolderA to CB4FolderD If NonNull.Key = 1 = True Then CheckA = True Done = True End If If NonNull.Key = 2 = True Then CheckB = True Done = True End If If NonNull.Key = 3 = Tru e Then CheckC = True Done = True End If If NonNull.Key = 4 = True Then CheckD = True Done = True End If Next Return Done End Function Private Function GetListOfFile s(ByVal Currentlocation As String, ByRef Done As Boolean) As String For Each eFilename As String In IO.Directory.GetFiles(Currentlocation, \"*\", IO.SearchOption.TopDirectoryOnly) Dim iFileName As String = System.IO.Path.GetFileName(eFilename) Dim NewDirNameCut As String = eFilename.Replace(iFileName, \"\") FileDetails.Add(iFileName, NewDirNameCut) CheckedListBox1.Items.Add(iFileName) Next Done = True Return Done End Function Private Function FileCopy(ByVal iLocation As String, ByVal iNewLocation As String, ByVal eFile As String, ByVal FileNameOnly As String, ByRef Done As Boolean) As Boolean If Directory.Exists(iNewLocation) = False Then My.Computer.FileSystem.CreateDirectory(iNewLocation) MessageBox.Show(\"folder created successfully, click OK\") End If If File.Exists(eFile) Then Dim OldFileToCopy = iLocation & FileNameOnly Dim NewFileToCopy = iNewLocation & FileNameOnly If System.IO.File.Exists(OldFileToCopy) = True Then System.IO.File.Copy(OldFileToCopy, NewFileToCopy, True) End If MessageBox.Show(\"File Copied From: \" & Environment.NewLine & iLocation & FileNameOnly & Environment.NewLine & \"To:\" & Environment.NewLine & iNewLocation & FileNameOnly) Done = True Return Done Else Done = False Return Done End If End Function #End Region #End RegionHi CokingK, I do still need your assistance if possible, I’ve managed as litle as possible to copy the file to Temp folder, I have a ScreenShot here and here is the code: #Region \"Declaration\" Dim FileDetails As New Dictionary(Of String, String) Dim CheckedItem As Integer = 0 Dim CheckedSelected As String = \"\" #End Region Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load End Sub #Region \"Subroutines\" Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click Dim result As DialogResult = FolderBrowserDialog1.ShowDialog() If Not result = Windows.Forms.DialogResult.Cancel Then GetListOfFiles(Currentlocation:=FolderBrowserDialog1.SelectedPath, NewLocation:=FolderBrowserDialog1.SelectedPath & \& \"\", Done:=False) End If End Sub Private Sub btnCopyFiles_Click(sender As Object, e As EventArgs) Handles btnCopyFiles.Click Dim NewLocation As String = TextBox1.Text Dim fdAr As String = CheckBox1.Text For Me.CheckedItem = 0 To CheckedListBox1.CheckedItems.Count - 1 CheckedSelected = CheckedListBox1.CheckedItems(CheckedItem).ToString If FileDetails.ContainsKey(CheckedSelected) Then ' Write value of the key. Dim zLocation As String = Nothing zLocation = FileDetails.Item(CheckedSelected) Dim Comparison As KeyValuePair(Of String, String) Dim ComparisonValue As String = Nothing Dim eFileNameOnly As String = Nothing For Each Comparison In FileDetails If Comparison.Key = CheckedSelected Then ComparisonValue = Comparison.Value & Comparison.Key eFileNameOnly = Comparison.Key FileCopy(iLocation:=zLocation, iNewLocation:=zLocation & NewLocation & \"\", eFile:=ComparisonValue, FileNameOnly:=eFileNameOnly, Done:=False) End If Next End If Next End Sub Private Function GetListOfFiles(ByVal Currentlocation As String, ByVal NewLocation As String, ByRef Done As Boolean) As String NewLocation = TextBox1.Text If Directory.Exists(NewLocation) = False Then If CheckBox1.CheckState = 1 Then My.Computer.FileSystem.CreateDirectory(\"\" & NewLocation & \"\ar\") MessageBox.Show(\"Arabic folder created successfully, click OK\") End If End If For Each eFilename As String In IO.Directory.GetFiles(Currentlocation, \"*\", IO.SearchOption.TopDirectoryOnly) Dim iFileName As String = System.IO.Path.GetFileName(eFilename) Dim NewDirNameCut As String = eFilename.Replace(iFileName, \"\") FileDetails.Add(iFileName, NewDirNameCut) CheckedListBox1.Items.Add(iFileName) Next Done = True Return Done End Function Private Function FileCopy(ByVal iLocation As String, ByVal iNewLocation As String, B yVal eFile As String, ByVal FileNameOnly As String, ByRef Done As Boolean) As Boolean If File.Exists(eFile) Then iNewLocation = TextBox1.Text Dim OldFileToCopy = iLocation & FileNameOnly Dim NewFileToCopy = iNewLocation & FileNameOnly If System.IO.File.Exists(OldFileToCopy) = True Then System.IO.File.Copy(OldFileToCopy, NewFileToCopy, True) End If MessageBox.Show(\"Copied: \" & iLocation & FileNameOnly & \" to \" & iNewLocation & FileNameOnly) Done = True Return Done Else Done = False Return Done End If End Function #End Region ScreenShotHow Do I do this? here is what I'm trying to do: A SCREENSHOT to what I'm trying to AchiveThis is the controls that I have created: Button1 "Browse..." to files, I'm using OpenFileDialog select the file(s) and add them into the CheckListBox1, TextBox1 contains path where the file(s) are copied to e.g. "D:\temp", Checkbox1, Checkbox2, Checkbox3 are folder that are created when checked under "D:\temp\folder1" if no CheckBox is checked no folder(s) are and no file(s) Button2 "Copy File(s)" when clicked folder(s) will be created and file(s) copied to the path of TextBox1 according to the Checkbox1, Checkbox2, Checkbox3 if they checked.This is the code that I have:Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim browseFiles As New OpenFileDialog browseFiles.Title = "Select files to copy" browseFiles.Filter = "All Files (*.*)|*.*" 'allow multiselection in the open file dialog browseFiles.Multiselect = True Dim result As DialogResult = browseFiles.ShowDialog() If Not result = Windows.Forms.DialogResult.Cancel Then 'here its file name(s) with s to return array of file names Dim names() As String = browseFiles.FileNames For Each name As String In names Dim fileName As String = System.IO.Path.GetFileName(name) CheckedListBox1.Items.Add(fileName) Next End IfEnd SubPrivate Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click Dim txt As String txt = TextBox1.Text If CheckBox1.CheckState = 1 Then My.Computer.FileSystem.CreateDirectory("" & txt & "\Folder1") MessageBox.Show("Folder1 created successfully, click OK") End If If CheckBox2.CheckState = 1 Then My.Computer.FileSystem.CreateDirectory("" & txt & "\Folder2") MessageBox.Show("Folder2 created successfully, click OK") End If If CheckBox3.CheckState = 1 Then My.Computer.FileSystem.CreateDirectory("" & txt & "\Folder3") MessageBox.Show("Folder3 created successfully, click OK") End If If CheckBox4.CheckState = 1 Then My.Computer.FileSystem.CreateDirectory("" & txt & "\Folder4") MessageBox.Show("Folder4 created successfully, click OK") End IfEnd Sub 解决方案 For a start, you are using the wrong control if you want to get a list of all files in a directory based on a folder path. (Unless you want specifically select these files only).You are using the OpenFileDialog when you would be better to use the OpenFolderDialog. I would only be using the OpenFileDialog if you want to choose which files you want to add manually, otherwise you could use recursive measures to do the work for you.The open folder dialog is all you need to return the folder path that your user has selected.You can use System.IO.DirectoryInfo to return directory info, and System.IO.FileInfo to return file info. To return a list of the files in that directory you can use the System.IO.Path as you have in your above example.You don't need this because the path will never be null if it can be selected. :)If Not String.IsNullOrEmpty(txtFolderPath.Text) ThenI rewrote it using the folderdialog instead. It is easy to change it back should you need too. This code is working perfectly fine and I have included a lot of functionality to allow you to play around with the file paths and file names which is why I used the dictionary for that.The code is not commented, but if you have any questions, let me know. If you are happy with this, please mark it as a solution.#Region "Declationss" Dim FileDetails As New Dictionary(Of String, String) Dim CheckedItem As Integer = 0 Dim CheckedSelected As String = ""#End Region#Region "Subroutines" Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim result As DialogResult = FolderBrowserDialog.ShowDialog() If Not result = Windows.Forms.DialogResult.Cancel Then GetListOfFiles(Currentlocation:=FolderBrowserDialog.SelectedPath, NewLocation:=FolderBrowserDialog.SelectedPath & "\" & "folder", Done:=False) End If End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click For Me.CheckedItem = 0 To CheckedListBox1.CheckedItems.Count - 1 CheckedSelected = CheckedListBox1.CheckedItems(CheckedItem).ToString If FileDetails.ContainsKey(CheckedSelected) Then ' Write value of the key. Dim zLocation As String = Nothing zLocation = FileDetails.Item(CheckedSelected) Dim Comparison As KeyValuePair(Of String, String) Dim ComparisonValue As String = Nothing Dim eFileNameOnly As String = Nothing For Each Comparison In FileDetails If Comparison.Key = CheckedSelected Then ComparisonValue = Comparison.Value & Comparison.Key eFileNameOnly = Comparison.Key FileCopy(iLocation:=zLocation, iNewLocation:=zLocation & "folder\", eFile:=ComparisonValue, FileNameOnly:=eFileNameOnly, Done:=False) End If Next End If Next End Sub#End Region#Region "Functions" Private Function GetListOfFiles(ByVal Currentlocation As String, ByVal NewLocation As String, ByRef Done As Boolean) As String If Directory.Exists(NewLocation) = False Then My.Computer.FileSystem.CreateDirectory(NewLocation) MessageBox.Show("folder created successfully, click OK") End If For Each eFilename As String In IO.Directory.GetFiles(Currentlocation, "*", IO.SearchOption.TopDirectoryOnly) Dim iFileName As String = System.IO.Path.GetFileName(eFilename) Dim NewDirNameCut As String = eFilename.Replace(iFileName, "") FileDetails.Add(iFileName, NewDirNameCut) CheckedListBox1.Items.Add(iFileName) Next Done = True Return Done End Function Private Function FileCopy(ByVal iLocation As String, ByVal iNewLocation As String, ByVal eFile As String, ByVal FileNameOnly As String, ByRef Done As Boolean) As Boolean If File.Exists(eFile) Then Dim OldFileToCopy = iLocation & FileNameOnly Dim NewFileToCopy = iNewLocation & FileNameOnly If System.IO.File.Exists(OldFileToCopy) = True Then System.IO.File.Copy(OldFileToCopy, NewFileToCopy, True) End If MessageBox.Show("Copied: " & iLocation & FileNameOnly & " to " & iNewLocation & FileNameOnly) Done = True Return Done Else Done = False Return Done End If End Function#End RegionHi, here is a another solution for you which works perfectly. So you can also mark this as a solution too. If you have any questions, please post your questions under my solution and I will get back to you when I have some free time. :)As you requested alterations for the checkboxes locations, I have provided two methods which are explained in the source code of Button2. Hope it helps you.#Region "MoveFiles Region"#Region "Declations" Dim FileDetails As New Dictionary(Of String, String) Dim CheckedItem As Integer = 0 Dim CheckedSelected As String = "" 'The CBCheckedFolders will be used to add the two directories together if they are both selected. Dim CBCheckedFolders As String = Nothing 'The CtrlDict Dictionary will be used to collect the new folder paths from your CheckBox Text property, and an integer to represent its position and state. Dim CtrlDict As New Dictionary(Of Integer, String) 'The Boolean variable(s) below will be true if a value in the CtrlDict = one of our checkstate keys added 'from our CheckBoxes Checked Changed Event. Dim CheckA, CheckB, CheckC, CheckD As Boolean Dim FolderBrowserPath As String = Nothing Dim SetLabelPath As String = "" Dim SetLabelPathCut As String = Nothing#End Region#Region "Subroutines" Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load LocationLabel.Visible = False LocationLabel.Text = "Location:" End Sub Private Sub CB1FolderA_CheckedChanged(sender As Object, e As EventArgs) Handles CB1FolderA.CheckedChanged If Me.CB1FolderA.CheckState = CheckState.Checked AndAlso FolderBrowserPath IsNot Nothing Then CtrlDict.Add(1, CB1FolderA.Text & "\") LocationLabel.Visible = True If Not SetLabelPath.Contains(CB1FolderA.Text) Then SetLabelPath = SetLabelPath + "\" + CB1FolderA.Text LocationLabel.Text = "Location: " & FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath End If ElseIf Me.CB1FolderA.CheckState = CheckState.Unchecked AndAlso FolderBrowserPath IsNot Nothing Then CtrlDict.Remove(1) LocationLabel.Visible = True If SetLabelPath.Contains(CB1FolderA.Text) Then SetLabelPathCut = SetLabelPath.Replace("\" & CB1FolderA.Text, "") SetLabelPath = SetLabelPathCut LocationLabel.Text = "Location: " & FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath End If Else MsgBox("Browse a folder first.") End If End Sub Private Sub CB2FolderB_CheckedChanged(sender As Object, e As EventArgs) Handles CB2FolderB.CheckedChanged If Me.CB2FolderB.CheckState = CheckState.Checked Then CtrlDict.Add(2, CB2FolderB.Text & "\") LocationLabel.Visible = True SetLabelPath = SetLabelPath + "\" + CB2FolderB.Text LocationLabel.Text = "Location: " & FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath ElseIf Me.CB2FolderB.CheckState = CheckState.Unchecked AndAlso FolderBrowserPath IsNot Nothing Then CtrlDict.Remove(2) LocationLabel.Visible = True If SetLabelPath.Contains(CB2FolderB.Text) Then SetLabelPathCut = SetLabelPath.Replace("\" & CB2FolderB.Text, "") SetLabelPath = SetLabelPathCut LocationLabel.Text = "Location: " & FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath End If LocationLabel.Text = "Location: " & FolderBrowserPath + SetLabelPath Else MsgBox("Browse a folder first.") End If End Sub Private Sub CB3FolderC_CheckedChanged(sender As Object, e As EventArgs) Handles CB3FolderC.CheckedChanged If Me.CB3FolderC.CheckState = CheckState.Checked AndAlso FolderBrowserPath IsNot Nothing Then CtrlDict.Add(3, CB3FolderC.Text & "\") LocationLabel.Visible = True SetLabelPath = SetLabelPath + "\" + CB3FolderC.Text LocationLabel.Text = "Location: " & FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath ElseIf Me.CB3FolderC.CheckState = CheckState.Unchecked AndAlso FolderBrowserPath IsNot Nothing Then CtrlDict.Remove(3) LocationLabel.Visible = True If SetLabelPath.Contains(CB3FolderC.Text) Then SetLabelPathCut = SetLabelPath.Replace("\" & CB3FolderC.Text, "") SetLabelPath = SetLabelPathCut LocationLabel.Text = "Location: " & FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath End If LocationLabel.Text = "Location: " & FolderBrowserPath + SetLabelPath Else MsgBox("Browse a folder first.") End If End Sub Private Sub CB4FolderD_CheckedChanged(sender As Object, e As EventArgs) Handles CB4FolderD.CheckedChanged If Me.CB4FolderD.CheckState = CheckState.Checked AndAlso FolderBrowserPath IsNot Nothing Then CtrlDict.Add(4, CB4FolderD.Text & "\") LocationLabel.Visible = True SetLabelPath = SetLabelPath + "\" + CB4FolderD.Text LocationLabel.Text = "Location: " & FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath ElseIf Me.CB4FolderD.CheckState = CheckState.Unchecked AndAlso FolderBrowserPath IsNot Nothing Then CtrlDict.Remove(4) LocationLabel.Visible = True If SetLabelPath.Contains(CB4FolderD.Text) Then SetLabelPathCut = SetLabelPath.Replace("\" & CB4FolderD.Text, "") SetLabelPath = SetLabelPathCut LocationLabel.Text = "Location: " & FolderBrowserPath + SetLabelPath CBCheckedFolders = SetLabelPath End If LocationLabel.Text = "Location: " & FolderBrowserPath + SetLabelPath Else MsgBox("Browse a folder first.") End If End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim result As DialogResult = FolderBrowserDialog.ShowDialog() If Not result = Windows.Forms.DialogResult.Cancel Then FolderBrowserPath = FolderBrowserDialog.SelectedPath GetListOfFiles(Currentlocation:=FolderBrowserDialog.SelectedPath, Done:=False) End If End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click For Me.CheckedItem = 0 To CheckedListBox1.CheckedItems.Count - 1 CheckedSelected = CheckedListBox1.CheckedItems(CheckedItem).ToString If FileDetails.ContainsKey(CheckedSelected) Then ' Write value of the key. Dim zLocation As String = Nothing zLocation = FileDetails.Item(CheckedSelected) Dim Comparison As KeyValuePair(Of String, String) Dim ComparisonValue As String = Nothing Dim eFileNameOnly As String = Nothing For Each Comparison In FileDetails If Comparison.Key = CheckedSelected Then ComparisonValue = Comparison.Value & Comparison.Key eFileNameOnly = Comparison.Key Dim Checked As Boolean If WhatsChecked(Done:=Checked) = True Then CombineChecked(RTCombinePath:=CBCheckedFolders) Dim LabelPathText As String = LocationLabel.Text Dim LabelPathTextCut As String = LabelPathText.Remove(0, 10)'#########################What You Need To Do#######################'You need to add one additional Label to your form called: LocationLabel'You need to rename your checkboxes on your form as they are named below:'CB1FolderA, CB2FolderB, CB3FolderC, CB4FolderD'Add a OpenFolderDiaLog with the name: OpenFolderDiaLog'Replace your Button1, and Button2 code with mine.'If you get stuck, or have questions, feel free to ask me in the comments.'########################How It Works###############################'Now, this part is important as I've wrote this in a way'that you have two methods, working differently, and they'both do the same job. They both do the job differently,'One of the options is using a Dictionary called: CtrlDict'It adds the value of a selected checkboxes text property'to a dictionary.value property.'We then use the dictionary.key property from the same'Dictionary (CtrlDict) in a function called: WhatsChecked'This checkes the dictionary keys against each checked'checkbox. Thus enabling a Boolean value to True for each'match found...'We then use the CombineChecked to those Boolean Values we'set in the: WhatsChecked function, and this returns the'enabled checkboxes text property for the checkboxes which'have a CheckState = to Checked. This gives you a variable'path: CBCheckedFolders with the Checkboxes text property's'added to the variable which is then used and passed on to'the function: FileCopy as you can see in the code from'button 2.'####################Additional Method###############################'So what is the commented line below the non-commented'FileCopy function? That is another method which you can'also use to pass on to the FileCopy Function, and its a lot'easier to work with than the dictionary method.'(I added the dictionary method to give you experience and'to show you alternatives to using other functionality to'broaden your ability to expand on the use of the code.)'Anyway, The non-commented out FileCopy method below uses a'LabelPathTextCut Variable which removed the text: Location'from the variable named: LabelPathText whcih is = to the'LocationLabel.Text property, and this gives you an absolute'path to the OpenFolderDialog and the Checked Checkboxes'text properties. And this is handled in the CheckedChanged'EventArgs. The SetLabelPathCut and SetLabelPath variables'handle the Checkboxes (Checked) Text properties and'combines them. And lastly; the LocationLabel.Text property'Is then equal to:'LocationLabel.Text = "Location: " & FolderBrowserPath + SetLabelPath'then we removed the (Location:) part in the: LabelPathTextCut'variable where you can pass it on to the FileCopy function.'Job done, and have fun with it, as it is all fully working, and'you can choose which method you like best and remove the alternative.'But If you break it, I won't be fixing it. :)'Now you can remove whatever functionality you don't like or want. '###############################END################################### FileCopy(iLocation:=zLocation, iNewLocation:=LabelPathTextCut & "\", eFile:=ComparisonValue, FileNameOnly:=eFileNameOnly, Done:=False) ' FileCopy(iLocation:=zLocation, iNewLocation:=zLocation & CBCheckedFolders, eFile:=ComparisonValue, FileNameOnly:=eFileNameOnly, Done:=False) End If 'Recently added in updated code. End If Next End If Next End Sub#End Region#Region "Functions" Private Function CombineChecked(ByRef RTCombinePath As String) As String 'Recently added in updated code. 'This will reset the RTCombinePath each time this function is run. RTCombinePath = Nothing Dim NonNull As KeyValuePair(Of Integer, String) For Each NonNull In CtrlDict 'Now we will write a new directory structure based on the order of the checkboxes. So from CB1FolderA to CB4FolderD 'Returning each one that was checked. With NonNull If CheckA = True Then 'The If Not statement ensures no duplicate additions are added. If Not CBCheckedFolders = Nothing AndAlso Not CBCheckedFolders.Contains(.Value) Then CBCheckedFolders = CBCheckedFolders + (.Value) ElseIf CBCheckedFolders = Nothing Then CBCheckedFolders = (.Value) End If End If If CheckB = True Then If Not CBCheckedFolders = Nothing AndAlso Not CBCheckedFolders.Contains(.Value) Then CBCheckedFolders = CBCheckedFolders + (.Value) ElseIf CBCheckedFolders = Nothing Then CBCheckedFolders = (.Value) End If End If If CheckC = True Then If Not CBCheckedFolders = Nothing AndAlso Not CBCheckedFolders.Contains(.Value) Then CBCheckedFolders = CBCheckedFolders + (.Value) ElseIf CBCheckedFolders = Nothing Then CBCheckedFolders = (.Key) End If End If If CheckD = True Then If Not CBCheckedFolders = Nothing AndAlso Not CBCheckedFolders.Contains(.Value) Then CBCheckedFolders = CBCheckedFolders + (.Value) ElseIf CBCheckedFolders = Nothing Then CBCheckedFolders = (.Value) End If End If End With Next RTCombinePath = CBCheckedFolders Return RTCombinePath End Function Private Function WhatsChecked(ByRef Done As Boolean) As Boolean 'Recently added in updated code. Dim NonNull As KeyValuePair(Of Integer, String) For Each NonNull In CtrlDict 'Add Individual ifs to check each key from the collection against each checkbox. 'Example, if NonNul.Key = a Numbered Integer, We know to enable that boolean: 'CheckA to = True. In this case, 1 , 2 , 3 , and 4 represent the first, second 'third and forth checkbox etc.... If NonNull.Key = 1 = False Then Done = False End If If NonNull.Key = 2 = False Then Done = False End If If NonNull.Key = 3 = False Then Done = False End If If NonNull.Key = 4 = False Then Done = False End If 'Now we will write a new directory structure based on the order of the checkboxes. So from CB1FolderA to CB4FolderD If NonNull.Key = 1 = True Then CheckA = True Done = True End If If NonNull.Key = 2 = True Then CheckB = True Done = True End If If NonNull.Key = 3 = True Then CheckC = True Done = True End If If NonNull.Key = 4 = True Then CheckD = True Done = True End If Next Return Done End Function Private Function GetListOfFiles(ByVal Currentlocation As String, ByRef Done As Boolean) As String For Each eFilename As String In IO.Directory.GetFiles(Currentlocation, "*", IO.SearchOption.TopDirectoryOnly) Dim iFileName As String = System.IO.Path.GetFileName(eFilename) Dim NewDirNameCut As String = eFilename.Replace(iFileName, "") FileDetails.Add(iFileName, NewDirNameCut) CheckedListBox1.Items.Add(iFileName) Next Done = True Return Done End Function Private Function FileCopy(ByVal iLocation As String, ByVal iNewLocation As String, ByVal eFile As String, ByVal FileNameOnly As String, ByRef Done As Boolean) As Boolean If Directory.Exists(iNewLocation) = False Then My.Computer.FileSystem.CreateDirectory(iNewLocation) MessageBox.Show("folder created successfully, click OK") End If If File.Exists(eFile) Then Dim OldFileToCopy = iLocation & FileNameOnly Dim NewFileToCopy = iNewLocation & FileNameOnly If System.IO.File.Exists(OldFileToCopy) = True Then System.IO.File.Copy(OldFileToCopy, NewFileToCopy, True) End If MessageBox.Show("File Copied From: " & Environment.NewLine & iLocation & FileNameOnly & Environment.NewLine & "To:" & Environment.NewLine & iNewLocation & FileNameOnly) Done = True Return Done Else Done = False Return Done End If End Function#End Region#End RegionHi CokingK, I do still need your assistance if possible, I've managed as litle as possible to copy the file to Temp folder, I have a ScreenShot here and here is the code:#Region "Declaration" Dim FileDetails As New Dictionary(Of String, String) Dim CheckedItem As Integer = 0 Dim CheckedSelected As String = ""#End Region Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load End Sub#Region "Subroutines" Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click Dim result As DialogResult = FolderBrowserDialog1.ShowDialog() If Not result = Windows.Forms.DialogResult.Cancel Then GetListOfFiles(Currentlocation:=FolderBrowserDialog1.SelectedPath, NewLocation:=FolderBrowserDialog1.SelectedPath & "\" & "", Done:=False) End If End Sub Private Sub btnCopyFiles_Click(sender As Object, e As EventArgs) Handles btnCopyFiles.Click Dim NewLocation As String = TextBox1.Text Dim fdAr As String = CheckBox1.Text For Me.CheckedItem = 0 To CheckedListBox1.CheckedItems.Count - 1 CheckedSelected = CheckedListBox1.CheckedItems(CheckedItem).ToString If FileDetails.ContainsKey(CheckedSelected) Then ' Write value of the key. Dim zLocation As String = Nothing zLocation = FileDetails.Item(CheckedSelected) Dim Comparison As KeyValuePair(Of String, String) Dim ComparisonValue As String = Nothing Dim eFileNameOnly As String = Nothing For Each Comparison In FileDetails If Comparison.Key = CheckedSelected Then ComparisonValue = Comparison.Value & Comparison.Key eFileNameOnly = Comparison.Key FileCopy(iLocation:=zLocation, iNewLocation:=zLocation & NewLocation & "", eFile:=ComparisonValue, FileNameOnly:=eFileNameOnly, Done:=False) End If Next End If Next End Sub Private Function GetListOfFiles(ByVal Currentlocation As String, ByVal NewLocation As String, ByRef Done As Boolean) As String NewLocation = TextBox1.Text If Directory.Exists(NewLocation) = False Then If CheckBox1.CheckState = 1 Then My.Computer.FileSystem.CreateDirectory("" & NewLocation & "\ar") MessageBox.Show("Arabic folder created successfully, click OK") End If End If For Each eFilename As String In IO.Directory.GetFiles(Currentlocation, "*", IO.SearchOption.TopDirectoryOnly) Dim iFileName As String = System.IO.Path.GetFileName(eFilename) Dim NewDirNameCut As String = eFilename.Replace(iFileName, "") FileDetails.Add(iFileName, NewDirNameCut) CheckedListBox1.Items.Add(iFileName) Next Done = True Return Done End Function Private Function FileCopy(ByVal iLocation As String, ByVal iNewLocation As String, ByVal eFile As String, ByVal FileNameOnly As String, ByRef Done As Boolean) As Boolean If File.Exists(eFile) Then iNewLocation = TextBox1.Text Dim OldFileToCopy = iLocation & FileNameOnly Dim NewFileToCopy = iNewLocation & FileNameOnly If System.IO.File.Exists(OldFileToCopy) = True Then System.IO.File.Copy(OldFileToCopy, NewFileToCopy, True) End If MessageBox.Show("Copied: " & iLocation & FileNameOnly & " to " & iNewLocation & FileNameOnly) Done = True Return Done Else Done = False Return Done End If End Function#End RegionScreenShot 这篇关于如何将多个文件从checkedListBox复制到文件夹VB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-31 08:02