hello can anybody tellme how i can check if exist and if not create
example
c:\abc.txt
if dont exist the EXE create with value 0
thanks all
Printable View
hello can anybody tellme how i can check if exist and if not create
example
c:\abc.txt
if dont exist the EXE create with value 0
thanks all
WAY 1: Simple Way
WAY TWO: The API wayCode:Private Sub Command1_Click()
If Dir("C:\abc.txt") <> "" Then
MsgBox "File exists"
Else
MsgBox "File does not exist"
'~~> Code here to create the text file
Dim i As Long
Open "C:\abc.txt" For Output As #1
For i = 0 To 5
Print #1, i
Next i
Close #1
End If
'~~> If the file has special attributes (eg: is Hidden)
'~~> you need to specify as below
'If Dir("C:\abc.txt", vbHidden) <> "" Then
'MsgBox "File exists"
'End If
End Sub
Code:Option Explicit
Private Declare Function OpenFile Lib "kernel32" (ByVal lpFileName As String, _
lpReOpenBuff As OFSTRUCT, ByVal wStyle As Long) As Long
Private Const OF_EXIST As Long = &H4000
Private Const OFS_MAXPATHNAME As Long = 128
Private Const HFILE_ERROR As Long = -1
Private Type OFSTRUCT
cBytes As Byte
fFixedDisk As Byte
nErrCode As Integer
Reserved1 As Integer
Reserved2 As Integer
szPathName(OFS_MAXPATHNAME) As Byte
End Type
Private Sub Command1_Click()
If FileExists("C:\abc.txt") = False Then
'~~> Your code to create the text File
Dim i As Long
Open "C:\abc.txt" For Output As #1
For i = 0 To 5
Print #1, i
Next i
Close #1
End If
End Sub
Private Function FileExists(ByVal Fname As String) As Boolean
Dim Ret As Long, Ofstr As OFSTRUCT
Ret = OpenFile(Fname, Ofstr, OF_EXIST)
If Ret <> HFILE_ERROR Then
FileExists = True
Else
FileExists = False
End If
End Function
ok but the question its:
if dont exist how i can make the program automatic create this file?
You can simply use Open For Output statement:
Code:Open ("C:\Test.txt" For Output As #1
'write to a file (if you have to)
Print #1, "Hello World!"
Close #1
I have updated the code above which answers both your questions :)
Edit: Rhino: You beat me to it :)
thanks all for the help