当前位置 博文首页 > VBS教程:fso方法-CreateTextFile 方法

    VBS教程:fso方法-CreateTextFile 方法

    作者:admin 时间:2021-02-09 21:22

    CreateTextFile 方法

    创建指定文件并返回 TextStream 对象,该对象可用于读或写创建的文件。

    object.CreateTextFile(filename[, overwrite[, unicode]])

    参数

    object

    必选项。应为 FileSystemObject 或 Folder 对象的名称。

    filename

    必选项。字符串表达式,指明要创建的文件。

    overwrite

    可选项。Boolean 值指明是否可以覆盖现有文件。如果可覆盖文件,该值为 True;如果不能覆盖文件,则该值为 False 。如果省略该值,则不能覆盖现有文件。

    unicode

    可选项。Boolean 值指明是否以 Unicode 或 ASCII 文件格式创建文件。如果以 Unicode 文件格式创建文件,则该值为 True;如果以 ASCII 文件格式创建文件,则该值为 False。如果省略此部分,则假定创建 ASCII 文件。

    说明

    以下代码举例说明如何使用 CreateTextFile 方法创建并打开文本文件:

    Sub CreateAfile Dim fso, MyFile
     Set fso = CreateObject("Scripting.FileSystemObject")
     Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
     MyFile.WriteLine("这是一个测试。") MyFile.CloseEnd Sub

    对于 filename 已经存在的文件,如果 overwrite 参数为 False,或未提供此参数时,则会出现错误。

    但很多时候为了方便,我们会自定义生成文本文件的函数

    Function createTextFile(Byval content,Byval fileDir,Byval code)
    	dim fileobj,fileCode : fileDir=replace(fileDir, "\", "/")
    	if isNul(code) then fileCode=Charset else fileCode=code
    	call createfolder(fileDir,"filedir")
    	if fileCode="utf-8" then
    		on error resume next
    		With objStream
    			.Charset=fileCode:
    			.Type=2:
    			.Mode=3:
    			.Open:
    			.Position=0
    			.WriteText content:
    			.SaveToFile Server.MapPath(fileDir), 2
    			.Close
    		End With
    	else
    		on error resume next:err.clear
    		set fileobj=objFso.CreateTextFile(server.mappath(fileDir),True)
    		fileobj.Write(content)
    		set fileobj=nothing
    	end if
    	if Err Then err.clear :createTextFile=false : errid=err.number:errdes=err.description:Err.Clear : echoErr err_09,errid,errdes else createTextFile=true
    End Function
    Sub echoErr(byval str,byval id, byval des)    
    
        dim errstr,cssstr
    		cssstr="<meta http-equiv=""Content-Type"" content=""text/html; charset="&Charset&""" />"
        cssstr=cssstr&"<style>body{text-align:center}#msg{background-color:white;border:1px solid #0073B0;margin:0 auto;width:400px;text-align:left}.msgtitle{padding:3px 3px;color:white;font-weight:700;line-height:28px;height30px;font-size:12px;border-bottom:1px solid #0073B0; text-indent:3px; background-color:#0073B0}#msgbody{font-size:12px;padding:20px 8px 30px;line-height:25px}#msgbottom{text-align:center;height:20px;line-height:20px;font-size:12px;background-color:#0073B0;color:#FFFFFF}</style>"
        errstr=cssstr&"<script language=""javascript"">setTimeout(""goLastPage()"",5000);function goLastPage(){location.href='"& sitePath &"/';}</script><div id='msg'><div class='msgtitle'>提示:【"&str&"】</div><div id='msgbody'>错误号:"&id&"<br>错误描述:"&des&"<br /><a href=""javascript:history.go(-1);"">返回上一页</a>&nbsp;<a href="""& sitePath &"/"">返回首页</a></div><div id='msgbottom'>Powered by AspCms2.0</div></div>"
        cssstr=""
        die(errstr)
    End Sub
    js
下一篇:没有了