61

我为自己编写了一个小的下载应用程序,这样我就可以轻松地从我的服务器中获取一组文件,并将它们全部放到一个全新安装了 Windows 的新电脑上,而无需真正上网。不幸的是,我在创建要放入它们的文件夹时遇到问题,并且不确定如何去做。

我希望我的程序将应用程序下载到program files\any name here\

所以基本上我需要一个函数来检查文件夹是否存在,如果不存在则创建它。

4

12 回答 12

179
If Not System.IO.Directory.Exists(YourPath) Then
    System.IO.Directory.CreateDirectory(YourPath)
End If
于 2008-09-17T18:12:41.243 回答
22

在 System.IO 下,有一个名为 Directory 的类。请执行下列操作:

If Not Directory.Exists(path) Then
    Directory.CreateDirectory(path)
End If

它将确保目录在那里。

于 2008-09-17T18:13:23.347 回答
11

试试System.IO.DirectoryInfo类。

来自 MSDN 的示例:

Imports System
Imports System.IO

Public Class Test
    Public Shared Sub Main()
        ' Specify the directories you want to manipulate.
        Dim di As DirectoryInfo = New DirectoryInfo("c:\MyDir")
        Try
            ' Determine whether the directory exists.
            If di.Exists Then
                ' Indicate that it already exists.
                Console.WriteLine("That path exists already.")
                Return
            End If

            ' Try to create the directory.
            di.Create()
            Console.WriteLine("The directory was created successfully.")

            ' Delete the directory.
            di.Delete()
            Console.WriteLine("The directory was deleted successfully.")

        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class
于 2008-09-17T18:12:59.963 回答
11

由于问题没有指定 .NET,这应该适用于 VBScript 或 VB6。

Dim objFSO, strFolder
strFolder = "C:\Temp"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists(strFolder) Then
   objFSO.CreateFolder(strFolder)
End If
于 2008-09-17T18:36:31.687 回答
7

试试这个:Directory.Exists(TheFolderName)Directory.CreateDirectory(TheFolderName)

(您可能需要Imports System.IO:)

于 2008-09-17T18:11:57.877 回答
5

VB.NET?System.IO.Directory.Exists(字符串路径)

于 2008-09-17T18:12:35.830 回答
4

Directory.CreateDirectory() 应该这样做。 http://msdn.microsoft.com/en-us/library/system.io.directory.createdirectory(VS.71).aspx

此外,在 Vista 中,您可能无法直接写入 C:,除非您以管理员身份运行它,因此您可能只想绕过它并在 C: 的子目录中创建所需的目录:(我想说的是无论如何都要遵循一个好的做法。 - 令人难以置信的是有多少人只是将垃圾扔到C上:

希望有帮助。

于 2008-09-17T18:15:26.680 回答
4

(导入 System.IO)

如果不是 Directory.Exists(Path) 则
  Directory.CreateDirectory(路径)
万一
于 2008-09-17T18:16:13.840 回答
3
If Not Directory.Exists(somePath) then
    Directory.CreateDirectory(somePath)
End If
于 2009-08-07T17:02:26.090 回答
1

您应该尝试使用文件系统对象或 FSO。该对象有许多方法可以检查文件夹是否存在以及创建新文件夹。

于 2008-09-17T18:13:58.730 回答
0

我知道这将如何工作,创建一个对话框的过程是什么,该对话框允许用户命名文件夹并将其放置在您想要的位置。

干杯

于 2009-03-24T02:12:56.490 回答
0

只需这样做:

        Dim sPath As String = "Folder path here"
    If (My.Computer.FileSystem.DirectoryExists(sPath) = False) Then
        My.Computer.FileSystem.CreateDirectory(sPath + "/<Folder name>")
    Else
        'Something else happens, because the folder exists
    End If

我将文件夹路径声明为字符串(sPath),这样如果您多次使用它,它可以轻松更改,但也可以通过程序本身进行更改。

希望能帮助到你!

-nfell2009

于 2013-10-16T17:30:38.683 回答