【问题标题】:VB.net Check items in a text doc and see if it's in a folderVB.net 检查文本文档中的项目并查看它是否在文件夹中
【发布时间】:2020-01-01 17:46:24
【问题描述】:

我有一个包含文件名及其扩展名列表的文本文档。我需要浏览此列表并检查目录中是否存在每个文件。然后我需要将结果输出到foundFilesList.txtOrphanedFiles.txt。我有两种方法来实现这个功能,但都不起作用。第一个示例使用循环在文本文档中循环。第二个不起作用,它永远不会看到来自 fileNamesList 的文件的匹配项。

感谢您抽出宝贵时间查看此内容。

第一个代码:

    Dim FILE_NAME As String

    FILE_NAME = txtFileName.Text
    Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
    fCount = 0
    For i = 0 To fileNames.Count() - 1
        Dim fileName = fileNames(i)
        'sFileToFind = location & "\" & fileName & "*.*"

        Dim paths = IO.Directory.GetFiles(location, fileName, IO.SearchOption.AllDirectories)
        If Not paths.Any() Then
            System.IO.File.AppendAllText(orphanedFiles, fileName & vbNewLine)
        Else
            For Each pathAndFileName As String In paths
                If System.IO.File.Exists(pathAndFileName) = True Then
                    Dim sRegLast = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
                    Dim toFileLoc = System.IO.Path.Combine(createXMLFldr, sRegLast)
                    Dim moveToFolder = System.IO.Path.Combine(MoveLocation, "XML files", sRegLast)

                    'if toFileLoc = XML file exists move it into the XML files folder
                    If System.IO.File.Exists(toFileLoc) = False Then
                        System.IO.File.Copy(pathAndFileName, moveToFolder, True)
                        System.IO.File.AppendAllText(ListofFiles, sRegLast & vbNewLine)
                        fileFilename = (fileName) + vbCrLf
                        fCount = fCount + 1
                        BackgroundWorker1.ReportProgress(fCount)
                        'fileCount.Text = fCount
                    End If
                End If
            Next
        End If
        BackgroundWorker1.ReportProgress(100 * i / fileNames.Count())
        'statusText = i & " of " & fileName.Count() & " copied"
        fCount = i
    Next

第二个代码:

    FILE_NAME = txtFileName.Text    'textfield with lines of filenames are located ]
    Dim fileNamesList = System.IO.File.ReadAllLines(FILE_NAME)
    location = txtFolderPath.Text
    fCount = 0


    ' Two list to collect missing and found files
    Dim foundFiles As List(Of String) = New List(Of String)()
    Dim notfoundFiles As List(Of String) = New List(Of String)()

    Dim fileNames As String() = System.IO.Directory.GetFiles(createXMLFldr)
    For Each file As String In fileNamesList
        Debug.Write("single file : " & file & vbCr)
        ' Check if the files is contained or not in the request list 
        Dim paths = IO.Directory.GetFiles(location, file, IO.SearchOption.AllDirectories)
        If fileNamesList.Contains(Path.GetFileNameWithoutExtension(file)) Then

            Dim FileNameOnly = Path.GetFileName(file)
            Debug.Write("FileNameOnly " & FileNameOnly & vbCr)
            If System.IO.File.Exists(FileNameOnly) = True Then
                'if toFileLoc = XML file exists move it into the XML files folder
                Dim moveToFolder = System.IO.Path.Combine(MoveLocation, "XML files", file)
                foundFiles.Add(file) 'add to foundFiles list                        
                fileFilename = (file) + vbCrLf  'add file name to listbox
                fCount = fCount + 1
            Else
                notfoundFiles.Add(file)
            End If
        End If
    Next
    File.WriteAllLines(ListofFiles, foundFiles)
    File.WriteAllLines(orphanedFiles, notfoundFiles)

【问题讨论】:

  • 尚不清楚您使用第一种方法得到的不良结果 - 您需要解释这一点。使用第二种方法,我不确定您为什么要测试文件文件夹 If fileNamesList.Contains(Path.GetFileNameWithoutExtension(file)) Then 是否存在。不过,我会为您的问题提出一个可能的解决方案。

标签: vb.net file-copying


【解决方案1】:

这只是你的一个起点,但请尝试一下:

Friend Module Main
  Public Sub Main()
    Dim oFiles As List(Of String)

    Dim _
      sOrphanedFiles,
      sSearchFolder,
      sFoundFiles,
      sTargetFile As String

    sOrphanedFiles = "D:\Results\OrphanedFiles.txt"
    sSearchFolder = "D:\Files"
    sFoundFiles = "D:\Results\FoundFiles.txt"
    oFiles = IO.File.ReadAllLines("D:\List.txt").ToList

    oFiles.ForEach(Sub(File)
                     If IO.Directory.GetFiles(sSearchFolder, File, IO.SearchOption.AllDirectories).Any Then
                       sTargetFile = sFoundFiles
                     Else
                       sTargetFile = sOrphanedFiles
                     End If

                     IO.File.AppendAllText(sTargetFile, $"{File}{Environment.NewLine}")
                   End Sub)
  End Sub
End Module

如果我对要求的判断有误,请告诉我,我会相应地更新。

【讨论】:

  • 这太好了,谢谢!我现在看看能不能用
  • 我收到 NullException 错误。值不能为空。参数名称路径。它突出显示 oFiles.ForEach 代码
  • @MaxineHammett ~ 您是否将我的示例文件/文件夹替换为您系统上的真实位置?
  • 是的,我做到了。我把困难的路径放进去。但我会再次测试
  • 是的,我再次检查并仍然收到错误。
【解决方案2】:

在线解释和cmets。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'I presume txtFileName.Text contains the full path including the file name
    'I also presume that this text file contains only file names with extensions
    Dim FilesInTextFile = System.IO.File.ReadAllLines(txtFileName.Text)
    'Instead of accessing the Directory over and over, just get an array of all the files into memory
    'This should be faster than searching the Directory structure one by one
    'Replace <DirectoryPathToSearch> with the actual path of the Directory you want to search
    Dim FilesInDirectory = IO.Directory.GetFiles("<DirectoryPathToSearch>", "*.*", IO.SearchOption.AllDirectories)
    'We now have an array of full path and file names but we just need the file name for comparison
    Dim FileNamesInDirectory = From p In FilesInDirectory
                               Select Path.GetFileName(p)
    'A string builder is more efficient than reassigning a string with &= because a 
    'string build is mutable
    Dim sbFound As New StringBuilder
    Dim sbOrphan As New StringBuilder
    'Instead of opening a file, writing to the file and closing the file 
    'in the loop, just append to the string builder
    For Each f In FilesInTextFile
        If FileNamesInDirectory.Contains(f) Then
            sbFound.AppendLine(f)
        Else
            sbOrphan.AppendLine(f)
        End If
    Next
    'After the loop write to the files just once.
    'Replace the file path with the actual path you want to use
    IO.File.AppendAllText("C:\FoundFiles.txt", sbFound.ToString)
    IO.File.AppendAllText("C:\OrphanFiles.txt", sbOrphan.ToString)
End Sub

【讨论】:

  • 与内联 cmets 的接触很好,玛丽 :-)
猜你喜欢
  • 2016-05-20
  • 2016-06-11
  • 2010-12-10
  • 2018-12-26
  • 1970-01-01
  • 2015-04-19
  • 2011-09-23
  • 2023-03-21
  • 1970-01-01
相关资源
最近更新 更多