【问题标题】:Search folder for file using the user input, then create copy of file使用用户输入在文件夹中搜索文件,然后创建文件副本
【发布时间】:2020-09-18 04:41:53
【问题描述】:

我正在尝试创建一个简单的程序,该程序将使用用户输入在特定文件夹中搜索图像,如果图像存在,然后将该图像的副本创建到另一个文件夹。用户可能没有全名,例如图片名称可以是iStock-454565767,用户可以只输入数字而没有istock

我们使用已购买的数千张 istock 照片并将它们保存在一个文件中,这使得搜索特定图像变得困难,尤其是当我们可能一次需要多张时。

我有这个代码:

Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
    Dim FSO, sourceFolder, currentFile, filesInSourceFolder
    Dim strSourceFolderPath As String
    Dim strDestinationFolderPath As String
    Dim strUserInput As String
    FSO = CreateObject("Scripting.FileSystemObject")

    strUserInput = txtSearch.Text
    strSourceFolderPath = "C:\Users\D41071023\Desktop\Photo Database"
    strDestinationFolderPath = "C:\Users\D41071023\Desktop\test"

    sourceFolder = FSO.GetFolder(strSourceFolderPath)
    filesInSourceFolder = sourceFolder.Files

    For Each currentFile In filesInSourceFolder
        If currentFile.Name = strUserInput Then
            currentFile.Copy(FSO.BuildPath(strDestinationFolderPath,
            currentFile.Name))
        End If
    Next
End Sub

当我点击“搜索”时,什么也没有发生。没有创建文件,甚至没有错误。另外,我想添加一个在创建文件时弹出的消息框,或者让用户知道找不到图像的消息。

【问题讨论】:

  • 你应该做类似If currentFile.Name.Contains(strUserInput)的事情,顺便说一句,使用IO.Filesystem类代替。
  • 如果您要使用 VB.NET,请使用它。 Directory.GetFilesFile.Copy 就是你所需要的。
  • 为什么用户不包含“iStock-”部分的事实意味着您的代码不能?

标签: asp.net .net vb.net


【解决方案1】:

据我了解,

Dim sourceFolderPath = "source folder path here" ' Folderpath without spaces
Dim fileNumber = "file number here"

Dim sourceFilePath = Directory.GetFiles(sourceFolderPath, $"iStock-{fileNumber}.png").FirstOrDefault()

If Not IsNothing(sourceFilePath) Then
    Dim destinationFolderPath = "destination folder path here" 'Folderpath without spaces
    Dim sourceFileName = Path.GetFileName(sourceFilePath)
    Dim destinationFilePath = Path.Combine(destinationFolderPath, sourceFileName)

    File.Copy(sourceFilePath, destinationFilePath)
    MsgBox("File " & "iStock-{fileNumber}.png" & " found.", MsgBoxStyle.OkOnly)
else 
    MsgBox("File not found  .  .  .  ", MsgBoxStyle.OkOnly + MsgBoxStyle.Information)
End If

【讨论】:

    【解决方案2】:

    如果我对您的理解正确,那么您应该拥有这样的东西:

    Dim sourceFolderPath = "source folder path here"
    Dim fileNumber = "file number here"
    
    Dim sourceFilePath = Directory.GetFiles(sourceFolderPath, $"iStock-{fileNumber}.png").SingleOrDefault()
    
    If sourceFilePath IsNot Nothing Then
        Dim destinationFolderPath = "destination folder path here"
        Dim sourceFileName = Path.GetFileName(sourceFilePath)
        Dim destinationFilePath = Path.Combine(destinationFolderPath, sourceFileName)
    
        File.Copy(sourceFilePath, destinationFilePath)
    End If
    

    【讨论】:

      猜你喜欢
      • 2013-08-31
      • 2017-04-14
      • 2019-08-07
      • 2021-11-23
      • 2022-01-17
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      相关资源
      最近更新 更多