如何使用VB创建一个文件夹和保存文件?

2024-11-23 16:02:43
推荐回答(4个)
回答1:

打开VB,新建一个标准EXE工程
在FORM1里添加控件:Command1、Text1、Picture1(位置自己排,TEXT1输入文件名)
然后双击窗体输入代码
Private Sub Command1_Click()
'//如果TEXT1的内容为空
If Text1.Text = "" Then MsgBox "请输入文件名", vbCritical, "错误": Exit Sub
'//如果文件不存在
If Dir(Text1.Text) = "" Then MsgBox "文件不存在", vbCritical, "错误": Exit Sub
'//打开文件并在PICTURE1里显示
Picture1.Picture = LoadPicture(Text1.Text)
'//判断C:\PIC\是否存在
If Dir("d:\pic\" & Date) = "" Then MkDir "d:\pic\" & Date
Dim i As Long
'//判断文件是否已经存在,存在则换一个名字
While (Dir("d:\pic\" & Date & "\" & i & ".bmp") <> "")
i = i + 1
Wend
'//储存文件
SavePicture Picture1.Picture, "d:\pic\" & Date & "\" & i & ".bmp"
End Sub

回答2:

呵呵.早上看到这个贴子时,写了一半的代码,结果发现贴子消失了..

怎么现在又冒出来了..

等等吧..我给你写.

完整代码来了:
==================================
'新建工程,1个按钮,1个text,1个Inet
'对text内容没做判断,对下载图片出错没做判断
'已测试,如果图片URL正确,且网络正确,程序是无问题的..

Private Sub Command1_Click()
Dim b() As Byte
Dim strURL As String

strURL = "http://www.baidu.com/img/" & Text1
b() = Inet1.OpenURL(strURL, icByteArray)

If Len(Dir("d:\pic", vbDirectory)) = 0 Then MkDir ("d:\pic")
If Len(Dir("d:\pic\" & Date, vbDirectory)) = 0 Then MkDir ("d:\pic\" & Date)

Open "d:\pic\" & Date & "\" & Text1 For Binary Access Write As #1
Put #1, , b()
Close #1
Picture1.Picture = LoadPicture("d:\pic\" & Date & "\" & Text1)
MsgBox "完成了!"
End Sub

Private Sub Form_Load()
Text1 = "sslm1_logo.gif"
Command1.Caption = "下载了!"
End Sub

回答3:

'//判断C:\PIC\是否存在
If Dir("d:\pic\" & Date) = "" Then MkDir "d:\pic\" & Date
Dim i As Long
'//判断文件是否已经存在,存在则换一个名字
While (Dir("d:\

回答4:

1、以下代码可以建立多级文件夹:
Option Explicit
Private Declare Function MakeSureDirectoryPathExists Lib "imagehlp.dll" (ByVal lpPath As String) As Long
'创建指定的目录(可以是多级目录)

Private Function CreateDirectory(ByVal sDirectory As String) As Boolean
'创建指定的目录(可以是多级目录),sDirectory:要创建的文件夹
On Error GoTo ErrHandle
Dim lngResult As Long
sDirectory = checkpath(sDirectory)
lngResult = MakeSureDirectoryPathExists(sDirectory)
CreateDirectory = IIf(lngResult = 0, False, True)
ErrHandle:
If Err <> 0 Then
CreateDirectory = False
End If
End Function

Private Function checkpath(ByVal sPath As String) As String
If Right$(sPath, 1) = "\" Then
checkpath = sPath
Else
checkpath = sPath & "\"
End If
End Function

Private Sub Command1_Click()
CreateDirectory "c:\abc\def\ghi"
End Sub

2~4、主要是文件的“打开”、“读取”、“保存”,多练习一下。下面的仅供参考,实际内容是很多的:
Open "D:\xxx.txt for append As #1
Print #1,"1234"
Print #1,"ABCD"
Close #1
'append 是以追加的方式操作的 还可以换成input,output等等 比如
Open "D:\xxx.txt for input As #1
do while not eof(1)
input #1,a
...
loop
Close #1
'上面的是打开和读取

5、一个判断
If Dir("c:\test.txt") = "" Then
MsgBox "指定文件不存在"
Else
MsgBox "指定文件存在"
End If