VB检查多个文件是不是存在

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了VB检查多个文件是不是存在相关的知识,希望对你有一定的参考价值。

文件:
1.jpg
2.jpg
3.exe
4.exe
5.qw
6.ewr
详细点
---------
别复制那些没有用的东西回来!

提问没有很具体,不知道是那种。
1 检查在某个具体目录下是否有这些文件存在。
2 检查整个电脑的硬盘看是否有这些文件。

如果是问题1,那有个简单的办法。直接用filelistbox控件,拉上来,不用改属性
程序中写
file1.path="c:\abc\"
里面就会显示出该目录下的所有文件

然后用程序依次判断就可以,如
for i= 1 to File1.ListCount
if file1.list(i-1)="1.jpg" then 说明找到了一个

next i

如果是问题2,则比较难
代码引自“源码天空”网站下载的程序源代码“文件搜索器”,没法粘界面图,你可以直接去下载源代码。以下代码供参考

Private Declare Function SHGetPathFromIDList Lib "Shell32.dll" Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Private Declare Function SHBrowseForFolder Lib "Shell32.dll" Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
Private Type BROWSEINFO '用于选择目录对话框的结构
hOwer As Long
pidlRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
ilmage As Long
End Type
Private Const BIF_RETURNONLYFSDIRS = &H1 '此常数的值待查
Private lindex As Long
Private Pflag As Boolean
'以下为显示文件属性对话框时用到的声明
Private Type SHELLEXECUTEINFO
cbSize As Long
fMask As Long
hwnd As Long
lpVerb As String
lpFile As String
lpParameters As String
lpDirectory As String
nShow As Long
hInstApp As Long
' Optional fields
lpIDList As Long
lpClass As String
hkeyClass As Long
dwHotKey As Long
hIcon As Long
hProcess As Long
End Type
Private Const SEE_MASK_INVOKEIDLIST = &HC
Private Const SEE_MASK_NOCLOSEPROCESS = &H40
Private Const SEE_MASK_FLAG_NO_UI = &H400
Private SEI As SHELLEXECUTEINFO
Private Declare Function ShellExecuteEX Lib "Shell32.dll" Alias "ShellExecuteEx" (SEI As SHELLEXECUTEINFO) As Long
'以下为利用API查找文件的声明
Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long
Private Const FILE_ATTRIBUTE_DIRECTORY = &H10
Private Const MAX_PATH = 260
Private Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type
Private Type WIN32_FIND_DATA
dwFileAttributes As Long
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReserved0 As Long
dwReserved1 As Long
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type

Private Sub Command1_Click()
Dim bi As BROWSEINFO
Dim rtn As String, pidl As String, path As String
Dim pos As Long
bi.hOwer = Me.hwnd
bi.lpszTitle = "请选择目录" '选择目录对话框
bi.ulFlags = BIF_RETURNONLYFSDIRS
pidl = SHBrowseForFolder(bi)
path = Space(512)
SHGetPathFromIDList pidl, path
pos = InStr(path, Chr(0))
rtn = Left(path, pos - 1)
If rtn = "" Then Exit Sub
Text1.Text = rtn
End Sub

Private Sub Command2_Click()
Dim fso As New FileSystemObject
On Error Resume Next
Pflag = False
Command3.Enabled = True
ListView1.ListItems.Clear
lindex = 1
Command2.Enabled = False
Screen.MousePointer = vbHourglass
StatusBar1.Panels(1).Text = "请稍侯..."
FindFile Trim(Text1.Text), Trim(Combo2.Text) '调用搜索过程
Command2.Enabled = True
Command3.Enabled = False
Screen.MousePointer = 0
StatusBar1.Panels(2).Text = "共有" & ListView1.ListItems.Count & "个文件"
StatusBar1.Panels(1).Text = "就绪"
End Sub
Private Sub FindFile(sPath As String, sFile As String)
Dim xf As WIN32_FIND_DATA
Dim ff As WIN32_FIND_DATA
Dim findhandle As Long
Dim lFindFile As Long
Dim Dstr As String
Dim fso As New FileSystemObject
Dim f As File
Dim cPath As String

On Error Resume Next
cPath = IIf(Len(sPath) > 3, sPath & "\", sPath)
lFindFile = FindFirstFile(cPath & sFile, ff)
StatusBar1.Panels(2).Text = "正在搜索 " & sPath
If lFindFile > 0 Then
Do
Set f = fso.GetFile(cPath & ff.cFileName)
ListView1.ListItems.Add lindex, , f.Name
ListView1.ListItems(lindex).SubItems(1) = f.ParentFolder
ListView1.ListItems(lindex).SubItems(2) = IIf(f.Size < 1024, Format(f.Size, "#### Byte"), Format(f.Size \ 1024, "###### KB"))
ListView1.ListItems(lindex).SubItems(3) = f.Type
ListView1.ListItems(lindex).SubItems(4) = Left(f.DateLastModified, Len(CStr(f.DateLastModified)) - 3)
lindex = lindex + 1
Loop Until (FindNextFile(lFindFile, ff) = 0)
FindClose lFindFile
If Pflag Then Exit Sub
End If
findhandle = FindFirstFile(cPath & "*.*", xf)
DoEvents
Do '注意这处判断是否为目录应使用与运算
If (xf.dwFileAttributes And FILE_ATTRIBUTE_DIRECTORY) Then
If Asc(xf.cFileName) <> Asc(".") Then
Dstr = cPath + Left(xf.cFileName, InStr(xf.cFileName, Chr(0)) - 1)
FindFile Dstr, sFile
End If
End If
If Pflag Then
FindClose findhandle
Exit Sub
End If
Loop Until (FindNextFile(findhandle, xf) = 0)
FindClose findhandle
End Sub

Private Sub Command3_Click()
Pflag = True
End Sub

Private Sub Command4_Click()
End
End Sub

Private Sub Form_Load()
ListView1.View = lvwReport
ListView1.ColumnHeaders.Add , , "文件名称"
ListView1.ColumnHeaders.Add , , "所在文件夹"
ListView1.ColumnHeaders.Add , , "大小"
ListView1.ColumnHeaders.Add , , "类型"
ListView1.ColumnHeaders.Add , , "修改日期"
ListView1.ColumnHeaders(2).Width = 3200
Combo2.AddItem "*.mp3"
Combo2.AddItem "*.wav"
Combo2.AddItem "*.mid"
Combo2.AddItem "*.gif"
Combo2.AddItem "*.avi"
Combo2.AddItem "*.rm"
Combo2.AddItem "*.swf"
Combo2.AddItem "*.jpg"
Combo2.AddItem "*.cur"
Combo2.AddItem "*.ico"
Combo2.Text = ""
Combo2.ListIndex = 0
End Sub

Private Sub ListView1_ItemClick(ByVal Item As MSComctlLib.ListItem)
Dim Fpath As String
On Error Resume Next
Image1.Stretch = False
Image1.Picture = LoadPicture(GPath(ListView1.SelectedItem.Index) & ListView1.SelectedItem.Text)
If Image1.Picture <> 0 Then
Label1.Visible = False
If Image1.Width > Picture1.ScaleWidth Then
Image1.Stretch = True
Image1.Width = Picture1.ScaleWidth
Image1.Left = 0
Else
Image1.Left = (Picture1.ScaleWidth - Image1.Width) / 2
End If
If Image1.Height > Picture1.ScaleHeight Then
Image1.Stretch = True
Image1.Height = Picture1.ScaleHeight
Image1.Top = 0
Else
Image1.Top = (Picture1.ScaleHeight - Image1.Height) / 2
End If
Image1.Visible = True
End If
End Sub

Private Sub ListView1_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)
If Button = 2 Then
PopupMenu popMenu
End If
End Sub

Private Sub mnuAttr_Click() '显示文件属性对话框
On Error Resume Next
With SEI
.cbSize = Len(SEI)
.fMask = SEE_MASK_NOCLOSEPROCESS Or SEE_MASK_INVOKEIDLIST Or SEE_MASK_FLAG_NO_UI
.hwnd = Form1.hwnd
.lpVerb = "properties"
.lpFile = GPath(ListView1.SelectedItem.Index) & ListView1.SelectedItem.Text
.lpDirectory = vbNullChar
.lpParameters = vbNullChar
.nShow = 0
.hInstApp = 0
.lpIDList = 0
.lpClass = vbNullChar
.hkeyClass = 0
.dwHotKey = 0
.hProcess = 0
.hIcon = 0
End With
ShellExecuteEX SEI
End Sub

Private Sub mnuCopy_Click()
Dim bi As BROWSEINFO
Dim rtn As String, pidl As String, path As String
Dim pos As Long
Dim fso As New FileSystemObject
Dim i As Long
bi.hOwer = Me.hwnd
bi.lpszTitle = "请选择目标文件夹"
bi.ulFlags = BIF_RETURNONLYFSDIRS
pidl = SHBrowseForFolder(bi)
path = Space(512)
SHGetPathFromIDList pidl, path
pos = InStr(path, Chr(0))
rtn = Left(path, pos - 1)
If rtn = "" Then Exit Sub
If Right(rtn, 1) <> "\" Then rtn = rtn & "\"
For i = 1 To ListView1.ListItems.Count
If ListView1.ListItems(i).Selected Then
fso.CopyFile GPath(i) & ListView1.ListItems(i).Text, rtn, True
End If
Next i
End Sub
Private Function GPath(i As Long)
GPath = IIf(Len(ListView1.ListItems(i).SubItems(1)) > 3, ListView1.ListItems(i).SubItems(1) & "\", ListView1.SelectedItem.SubItems(1))
End Function

Private Sub mnuDel_Click()
Dim fso As New FileSystemObject
Dim i As Long
Dim listCount As Long
For i = 1 To ListView1.ListItems.Count
If ListView1.ListItems(i).Selected Then
fso.DeleteFile GPath(i) & ListView1.ListItems(i).Text
End If
Next i
listCount = ListView1.ListItems.Count
Do While listCount > 0
If ListView1.ListItems(listCount).Selected Then
ListView1.ListItems.Remove listCount
End If
listCount = listCount - 1
Loop
End Sub

Private Sub mnuRename_Click()
Dim tmp As String
tmp = InputBox("将文件名改为:", "文件改名", ListView1.SelectedItem.Text)
On Error GoTo err
Name GPath(ListView1.SelectedItem.Index) & ListView1.SelectedItem.Text As GPath(ListView1.SelectedItem.Index) & tmp
ListView1.SelectedItem.Text = tmp
err:
End Sub

Private Sub mnuRevSelect_Click()
Dim i As Long
For i = 1 To ListView1.ListItems.Count
ListView1.ListItems(i).Selected = Not ListView1.ListItems(i).Selected
Next
End Sub

Private Sub mnuSelectAll_Click()
Dim i As Long
For i = 1 To ListView1.ListItems.Count
ListView1.ListItems(i).Selected = True
Next i
End Sub

Private Sub mnuSelectNone_Click()
Dim i As Long
For i = 1 To ListView1.ListItems.Count
ListView1.ListItems(i).Selected = False
Next
End Sub
参考技术A dir

如何检查 vb .net 项目的 sql server 中是不是存在数据库和表?

【中文标题】如何检查 vb .net 项目的 sql server 中是不是存在数据库和表?【英文标题】:How to check if a database and tables exist in sql server in a vb .net project?如何检查 vb .net 项目的 sql server 中是否存在数据库和表? 【发布时间】:2014-08-06 14:19:27 【问题描述】:

谁能告诉我如何检查来自 vb.net 项目的 sql server 中是否存在数据库和表?我想要做的是检查数据库是否存在(最好在'If'语句中,除非有人有更好的方法)如果它确实存在我做一件事,如果它不存在我创建数据库与表格和列。对此问题的任何帮助将不胜感激。

编辑:

应用程序与服务器建立了连接。当应用程序在 PC 上运行时,我希望它检查数据库是否存在,如果存在,那么它会继续执行它应该做的事情,但是如果数据库不存在,那么它首先创建数据库,然后继续执行它应该做什么。所以基本上我希望它第一次在 PC 上运行时创建数据库,然后开始它的业务,然后每次它在 PC 上运行时,我希望它看到数据库存在,然后开始它的业务。我想要这样的原因是因为这个应用程序将在不止一台 PC 上,我只希望创建一次数据库和表(第一次在 PC 上运行),然后当它在另一台 PC 上运行时,它看到数据库已经存在,然后使用在另一台 PC 上创建的现有数据库运行应用程序。

【问题讨论】:

我假设您的应用程序必须已经连接到服务器?这对我来说听起来像是一个部署,而不是你应该嵌入到应用程序中的东西。您可以检查 sys.databases 我认为与服务器的连接不是问题。我假设应用程序可以动态创建数据库和表,如果它们不存在的话。 这将向您展示如何检查:kellyschronicles.wordpress.com/2009/02/16/…,我会将其发布为答案,但它只是复制粘贴工作。 @Tanner 您的链接效果很好,感谢您的帮助。问题解决了。 @Coder92 没问题,我会尽快将其添加为参考答案 【参考方案1】:

您可以查询 SQL Server 以检查对象是否存在。

要检查数据库是否存在,您可以使用以下查询:

SELECT * FROM master.dbo.sysdatabases WHERE name = 'YourDatabase'

要检查表是否存在,您可以对目标数据库使用此查询:

SELECT * FROM sys.tables WHERE name = 'YourTable' AND type = 'U'

以下链接向您展示了如何使用 VB.NET 代码检查数据库是否存在是 SQL Server:

Check if SQL Database Exists on a Server with vb.net

以上链接中的参考代码:

Public Shared Function CheckDatabaseExists(ByVal server As String, _
                                           ByVal database As String) As Boolean
    Dim connString As String = ("Data Source=" _
                + (server + ";Initial Catalog=master;Integrated Security=True;"))

    Dim cmdText As String = _
       ("select * from master.dbo.sysdatabases where name=\’" + (database + "\’"))

    Dim bRet As Boolean = false

    Using sqlConnection As SqlConnection = New SqlConnection(connString)
        sqlConnection.Open
        Using sqlCmd As SqlCommand = New SqlCommand(cmdText, sqlConnection)
            Using reader As SqlDataReader = sqlCmd.ExecuteReader
                bRet = reader.HasRows
            End Using
        End Using
    End Using

    Return bRet

End Function

您可以通过另一种方式执行检查,因此通过使用 EXISTS 同时检查数据库和表在一次调用中完成:

IF NOT EXISTS (SELECT * FROM master.dbo.sysdatabases WHERE name = 'YourDatabase')
BEGIN
    -- Database creation SQL goes here and is only called if it doesn't exist
END

-- You know at this point the database exists, so check if table exists

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'YourTable' AND type = 'U')
BEGIN
    -- Table creation SQL goes here and is only called if it doesn't exist
END

上面的代码调用一次,参数为数据库和表名,就知道两者都存在。

【讨论】:

【参考方案2】:

连接主数据库并选择

SELECT 1 FROM master..sysdatabases WHERE name = 'yourDB'

然后在数据库上

SELECT 1 FROM INFORMATION_SCHEMA.TABLES  WHERE TABLE_NAME = 'yourTable'

我不知道确切的 vb 语法,但您只需检查结果中的记录数

【讨论】:

这会起作用,但会在代码方面产生问题,如果数据库或表不存在,您需要检查 NULL(无)。更好地使用 IF EXISTS(.....) SELECT 1 ELSE SELECT 0 所以总是保证返回。 哦,讽刺的是 @deterministicFail 在没有确定性失败的代码上得到纠正...... @Steve 在我的最后一句话中,我假设检查结果集的计数。所以 if 将在 vb 中而不是在 T-SQL 中 别忘了检查架构。 AND TABLE_SCHEMA = 'yourSchema' 关键是您可以获得结果 1 或 0 而无需返回 DataSet。只是一个 ExecuteScalar,它的性能更高。但是,在这种情况下,它并不重要。只是为了让您知道。【参考方案3】:

对于数据库中的表和其他对象,我通常这样做,但这确实是个人喜好。

IF OBJECT_ID('dbo.blah') IS NOT NULL
BEGIN

END

对于 VB.NET,我会将其包装在一个存储过程中并调用它。我相信 Linq 也有办法做到这一点。

【讨论】:

【参考方案4】:

您可以使用此查询来检查数据库

IF DB_Id('YourDatabaseName') 不为空

开始

PRINT 'DB EXISTS'

结束

否则

开始

PRINT 'DB  NOT EXISTS'

结束

【讨论】:

【参考方案5】:
Friend Function CheckDatabaseExists(server As String, database As String) As Boolean
    Dim connString As String = "Data Source=" + server + ";Initial Catalog=master;Integrated Security=SSPI"

    Dim cmdText As String = "select * from master.dbo.sysdatabases where name='" + database + "'"

    Dim bRet As Boolean = False

    Using sqlConnection As SqlConnection = New SqlConnection(connString)
        sqlConnection.Open
        Using sqlCmd As SqlCommand = New SqlCommand(cmdText, sqlConnection)
            Using reader As SqlDataReader = sqlCmd.ExecuteReader
                bRet = reader.HasRows
            End Using
        End Using
    End Using

    Return bRet

End Function

【讨论】:

【参考方案6】:
   Public Function SQLDatabaseExist(ByVal DefaultConnectionString As String, ByVal DataBaseName As String) As Boolean
    Try
        'CREATE DATABASE
        Dim SqlString As String = ""
        SqlString = "SELECT CASE WHEN EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'" & DataBaseName & "') THEN CAST (1 AS BIT) ELSE CAST (0 AS BIT) END"
        Dim ExcRet As Integer = 0
        Using connection As New SqlConnection(DefaultConnectionString)
            Dim command As New SqlCommand(SqlString, connection)
            command.Connection.Open()
            ExcRet = command.ExecuteScalar()
            command.Connection.Close()
            command.Dispose()
        End Using
        Return ExcRet
    Catch ex As Exception
        Return False
    End Try
End Function

【讨论】:

'示例默认连接字符串 Dim DefaultConnectionString As String = "Data Source=localhost\SQLSERVER2008;Initial Catalog=Master; User ID=SA; Password='123123'; MultipleActiveResultSets=false; Connect Timeout=15 ;加密=假;数据包大小=4096;" '注意连接字符串中的初始目录必须是master!

以上是关于VB检查多个文件是不是存在的主要内容,如果未能解决你的问题,请参考以下文章

检查 VB.net 的 DataTable 中是不是存在值的最简单/最快的方法?

如何检查 vb .net 项目的 sql server 中是不是存在数据库和表?

VB.net 在连接之前检查数据库是不是存在

从VB6检查访问中的假期表中是不是存在日期

检查多个文件中是不是存在多个字符串

检查Java中是不是存在多个文件