FSO - FileSystemObject 或 Scripting.FileSystemObject 的縮寫,為 IIS 內建群組件,用於操作磁碟、檔案夾或文字檔。FSO 的對象、方法和屬性非常的多,這裡用樣本的方式列出常用的,注意:《VBScript 語言參考》或《JScript 語言參考》中的:《FileSystemObject 使用者指南》和《Scripting 執行階段程式庫參考》便是微軟給出的 FileSystemObject 完整參考。
FSO 不能操作二進位檔案,要操作二進位檔案,請使用:ADODB.Stream。
建立檔案
dim fso, f
set fso = server.CreateObject("Scripting.FileSystemObject")
set f = fso.CreateTextFile("C:\test.txt", true) '第二個參數表示目標檔案存在時是否覆蓋
f.Write("寫入內容")
f.WriteLine("寫入內容並換行")
f.WriteBlankLines(3) '寫入三個空白行(相當於在文字編輯器中按三次斷行符號)
f.Close()
set f = nothing
set fso = nothing
開啟並讀檔案
dim fso, f
set fso = server.CreateObject("Scripting.FileSystemObject")
set f = fso.OpenTextFile("C:\test.txt", 1, false) '第二個參數 1 表示唯讀開啟,第三個參數表示目標檔案不存在時是否建立
f.Skip(3) '將當前位置向後移三個字元
f.SkipLine() '將當前位置移動到下一行的第一個字元,注意:無參數
response.Write f.Read(3) '從當前位置向後讀取三個字元,並將當前位置向後移三個字元
response.Write f.ReadLine() '從當前位置向後讀取直到遇到分行符號(不讀取分行符號),並將當前位置移動到下一行的第一個字元,注意:無參數
response.Write f.ReadAll() '從當前位置向後讀取,直到檔案結束,並將當前位置移動到檔案的最後
if f.atEndOfLine then
response.Write("一行的結尾!")
end if
if f.atEndOfStream then
response.Write("檔案的結尾!")
end if
f.Close()
set f = nothing
set fso = nothing
開啟並寫檔案
dim fso, f
set fso = server.CreateObject("Scripting.FileSystemObject")
set f = fso.OpenTextFile("C:\test.txt", 2, false) '第二個參數 2 表示重寫,如果是 8 表示追加
f.Write("寫入內容")
f.WriteLine("寫入內容並換行")
f.WriteBlankLines(3) '寫入三個空白行(相當於在文字編輯器中按三次斷行符號)
f.Close()
set f = nothing
set fso = nothing
判斷檔案是否存在
dim fso
set fso = server.CreateObject("Scripting.FileSystemObject")
if fso.FileExists("C:\test.txt") then
response.Write("目標檔案存在")
else
response.Write("目標檔案不存在")
end if
set fso = nothing
移動檔案
dim fso
set fso = server.CreateObject("Scripting.FileSystemObject")
call fso.MoveFile("C:\test.txt", "D:\test111.txt") '兩個參數的檔案名稱部分可以不同
set fso = nothing
複製檔案
dim fso
set fso = server.CreateObject("Scripting.FileSystemObject")
call fso.CopyFile("C:\test.txt", "D:\test111.txt") '兩個參數的檔案名稱部分可以不同
set fso = nothing
刪除檔案
dim fso
set fso = server.CreateObject("Scripting.FileSystemObject")
fso.DeleteFile("C:\test.txt")
set fso = nothing
建立檔案夾
dim fso
set fso = server.CreateObject("Scripting.FileSystemObject")
fso.CreateFolder("C:\test") '目標檔案夾的父資料夾必須存在
set fso = nothing
判斷檔案夾是否存在
dim fso
set fso = server.CreateObject("Scripting.FileSystemObject")
if fso.FolderExists("C:\Windows") then
response.Write("目標檔案夾存在")
else
response.Write("目標檔案夾不存在")
end if
set fso = nothing
刪除檔案夾
dim fso
set fso = server.CreateObject("Scripting.FileSystemObject")
fso.DeleteFolder("C:\test") '檔案夾不必為空白
set fso = nothing