2014-05-16 3 views
0

한 폴더에서 다른 폴더로 필요한 특정 파일을 복사하는 프로그램을 작성하고 있습니다. 그러나 특정 조건에 맞는 파일 만 복사하려고합니다. 구체적으로 금지 된 파일, 금지 된 확장자 또는 금지 된 폴더 목록에없는 파일은 다음과 같은 배열에 복사해야합니다.폴더를 반복하고 특정 조건과 일치하는 파일 만 복사하십시오.

Public BannedExtensions As String() = {".bak", ".bak2", ".cry", ".max", ".psd", 
     "log", ".lib", "pdb", ".exp"} 
Public BannedFolders As String() = {"Tools", "Editor", "Code", "LogBackups", 
     "statoscope", "BinTemp", "USER", "rc"} 
Public BannedFiles As String() = {"Editor.exe", "error.bmp", "error.dmp", 
     "luac.out", "tags.txt"} 

코드는이를 임시 디렉터리로 이동 한 다음 압축하여 File_Name 변수에 저장된 위치에 저장해야합니다.

이 전체적으로 내 코드입니다 : 나는 몇 가지 질문을

Option Strict On 
Public Class Form1 

    'define the two variables used for tracking file name and where to save' 
    Private Property Root_Folder As String 
    Private Property File_Name As String 

    'define the variable which dictates wether we copy the file 
    Private Property copy As Boolean 

    'define which files we need and do not need' 
    Public BannedExtensions As String() = {".bak", ".bak2", ".cry", ".max", ".psd", "log", ".lib", "pdb", ".exp"} 
    Public BannedFolders As String() = {"Tools", "Editor", "Code", "LogBackups", "statoscope", "BinTemp", "USER", "rc"} 
    Public BannedFiles As String() = {"Editor.exe", "error.bmp", "error.dmp", "luac.out", "tags.txt"} 

    Function Copy_RequiredFiles() As Integer 
     Dim i As Integer = 0 

     'Searches directory and it's subdirectories for all files, which "*" stands for 
     'Say for example you only want to search for jpeg files... then change "*" to "*.jpg" 
     For Each filename As String In IO.Directory.GetFiles(Root_Folder, "*", IO.SearchOption.AllDirectories) 

      copy = True 

      Dim fName As String = IO.Path.GetFileName(filename) 
      Dim fExtension As String = IO.Path.GetExtension(filename) 
      Dim fFolder As String = IO.Path.GetDirectoryName(filename) 

      For i = 0 To BannedExtensions.Length - 1 
       If fExtension = BannedExtensions(i) Then 
        RichTextBox1.Text = RichTextBox1.Text & vbNewLine & "Extension: " & filename 
        copy = False 
       End If 
      Next 
      If copy = True Then 
       i = 0 
       For i = 0 To BannedFolders.Length - 1 
        If filename = BannedFolders(i) Or BannedFolders(i).Contains(filename) Then 
         RichTextBox1.Text = CStr(CBool(RichTextBox1.Text & vbNewLine & "Folder: " & 
         copy) = False) 
        End If 
       Next 
       If copy = True Then 
        i = 0 
        For i = 0 To BannedFiles.Length - 1 
         If filename = BannedFolders(i) Or BannedFolders(i).Contains(filename) Then 
          RichTextBox1.Text = RichTextBox1.Text & vbNewLine & "Folder: " & filename 
          copy = False 
         End If 
        Next 
       End If 
      End If 
      If copy = True Then 
       'copy the file into the selected folder' 
      End If 
     Next 
     Return 0 
    End Function 

    'when the browse button for selecting the folder is selected' 
    Private Sub Browse_Root_Click(sender As Object, e As EventArgs) Handles Browse_Root.Click 
     'check if the folder dialogue has been opened successfully and something has been selected' 
     If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then ' 
      'set the textbox and the previously defined variable to the folder selected' 
      TextBox1.Text = FolderBrowserDialog1.SelectedPath 
      Root_Folder = FolderBrowserDialog1.SelectedPath 
     End If 
    End Sub 

    'when the browse button for where to save the file is selected' 
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     'set the options to limit the save type to a zip file' 
     SaveFileDialog1.Filter = "zip files (*.zip)|*.zip" 
     'check that the dialogue box has opened succesfully' 
     If SaveFileDialog1.ShowDialog() = DialogResult.OK Then 
      'set the text box and the previously defined variable to the file selected' 
      TextBox2.Text = SaveFileDialog1.FileName() 
      File_Name = SaveFileDialog1.FileName() 
     End If 
    End Sub 

    'when the user changes the value of the textbox update the folder to select from' 
    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged 
     Root_Folder = TextBox1.Text 
    End Sub 

    'when the user changes the value of the textbox update the file to save to' 
    Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged 
     File_Name = TextBox2.Text 
    End Sub 

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 
     Copy_RequiredFiles() 
    End Sub 
End Class 


'when the browse button for selecting the folder is selected' 
Private Sub Browse_Root_Click(sender As Object, e As EventArgs) Handles Browse_Root.Click 
    'check if the folder dialogue has been opened successfully and something has been selected' 
    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then ' 
     'set the textbox and the previously defined variable to the folder selected' 
     TextBox1.Text = FolderBrowserDialog1.SelectedPath 
     Root_Folder = FolderBrowserDialog1.SelectedPath 
    End If 
End Sub 

'when the browse button for where to save the file is selected' 
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    'set the options to limit the save type to a zip file' 
    SaveFileDialog1.Filter = "zip files (*.zip)|*.zip" 
    'check that the dialogue box has opened succesfully' 
    If SaveFileDialog1.ShowDialog() = DialogResult.OK Then 
     'set the text box and the previously defined variable to the file selected' 
     TextBox2.Text = SaveFileDialog1.FileName() 
     File_Name = SaveFileDialog1.FileName() 
    End If 
End Sub 

'when the user changes the value of the textbox update the folder to select from' 
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged 
    Root_Folder = TextBox1.Text 
End Sub 

'when the user changes the value of the textbox update the file to save to' 
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged 
    File_Name = TextBox2.Text 
End Sub 

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 
    Copy_RequiredFiles() 
End Sub 
End Class 

,

최초의, 왜 내가 프로그램을 실행하고 그것이 shouldn 것을 발견 파일을 인쇄 할 때 복사하지 않으면 루프의 두 번째 또는 세 번째 if 문에서 아무것도 표시되지 않습니다.

두 번째의 임시 파일을 복사 할 때 폴더 구조를 보존 할 방법이다.

그리고 세 번째는이 임시 폴더를 압축하는 최선의 방법이 무엇인지입니다. 사전에

감사합니다, 마커스

+0

'는 두 번째 또는 세 번째에서 아무것도 표시되지 않는 경우 loop' 거짓 밖으로 시작 블록 경우 첫 번째 변경되지 않습니다, 그래서 2, 3 실행되지 않을 copy' 변수'의 문. – Plutonix

+0

사실 복사는 내가 볼 수있는 사실로 설정되지 않습니다. – thetimmer

+0

지적 해 주셔서 고맙습니다. 게시물을 업데이트 할 것입니다. 검사를하지 않고 시작했지만 아직 작동하지 않았습니다. – marcus

답변

1

한 방향 정보를 저장하기 위해 목록에서 사용자 정의 클래스를 사용하는 것입니다 :

Class myFile 
    ' to do all the things you want ("preserve folder struct"), 
    ' you need more than a name in a textbox: 
    Public Property FileName As String 
    Public Property FileExt As String 
    Public Property PathName As String 

    ' cant create a new obj without the essential info 
    Public Sub New(fName As String, fExt as String, pName As String) 
     FileName = fName 
     FileExt = fExt 
     PathName = pName 
    End SUb 

End Class 

또는보다는 휠을 다시, System.IO.FileInfo 변경을 사용하여 파일을 반복하는 방법. 다음 목록은 이러한 것들을 저장하기 :

Friend myFileList As List(of myFile) 
' or 
Friend myFileList As List(of FileInfo) 

는 (의 myfile) 목록에 저장 반복하려면이 복사하는 코드 및 붙여 넣기보다 더 개념이다

Dim myF As MyFile 
For Each filename As String In IO.Directory.GetFiles 

    ' if BannedFiles is a List(Of String) instead of an array: 
    If BannedFiles.Contains(f.Extension) = False Then 
     ' create NEW file object with the info 
     myF = New MyFile(IO.Path.GetFileName(filename), 
          IO.Path.GetExtension(filename), 
          IO.Path.GetDirectoryName(filename)) 
     ' add to the list of files to do 
     myFileList.Add(f) 
    End If 

    If myFileList.Contains(f) = False Then   ' better version of Copy=true 
     For n As Integer = 0 To BannedFoldersLIST.Count - 1 
      If f.FullPath.Contains(BannedFoldersLIST(n)) = False Then 

       ' create a new file object as above 
       myFileList.Add(f)    ' add for folder ban 
      End If 
     Next n 
    End If 

    ' repeat for banned extensions (watch out for "." vs no dot) 

    Return myFileList    ' mine is a function returning 
           ' a List(Of T) to be processed elsewhere 

. 결과와 함께 여러 가지 작업을 수행하려는 경우 TextBox가 아닌 다른 항목에 저장하는 것이 좋습니다. VS는 마우스 목록에있는 내용을 즐겁게 보여줍니다.

폴더 테스트는 금지 된 문자열은 전체 또는 부분 이름인지 여부에 따라 작업을해야합니다. 큰 점은 전역 플래그 대신 .Contains을 사용하여 이미 항목을 저장 한 경우 List 객체가 알려주는 점입니다. List(Of FileInfo) 또는 List(Of myFileClass)이 작동합니다. 후자는 더 많은 코드를 보존합니다.