VB.NET文件對象讀寫文本文件
我們編程人員在日常的工作中往往都會面對多種編程語言的應(yīng)用。那么其中VB.NET這一語言的應(yīng)用平率是非常高的。我們首先通過一段對VB.NET文件對象的操作示例來初步解讀這門語言的應(yīng)用技巧。
VB.NET文件對象代表了一個文件,而且有一些非常有用的方法來檢驗一個文件的存在以及重命名和刪除一個文件。例如:
- Dim fl as File
- fl=new File("foo.txt")
- if(fl.Exists)
'if the file exists- fl.Delete 'delete it
- End If
用戶也可以使用File對象來獲取一個FileStream對象,然后通過使用FileStream對象來讀寫文件數(shù)據(jù):
- Dim ts as TextStream
- Dim fs as FileStream
- ts=fl.OpenText
'open a text file
for reading- fs=fl.OpenRead
'open any file for
reading
(1)VB.NET文件對象讀取一個文本文件(TextFile)
為了讀取一個文本文件,用戶可以使用File對象去獲取一個StreamReader對象,然后使用文本流(text stream)的讀取方法:
- Dim ts as StreamReader
- ts=fl.OpenText()
- s=ts.readLine
(2)VB.NET文件對象寫一個文本文件(Write a Text File)
要建立和寫一個文本文件,用戶可以用CreateText方法得到一個StreamWrite對象,然后進行操作,比如:
- Dim sw as streamWriter
- sw=fl.CreateText
- sw.writeLine
("write text into file")
如果用戶想對一個已經(jīng)存在的文件進行操作,可以使用一個帶有邏輯參數(shù)的對象來進行操作:
- sw=new StreamWriter
(path,true)
VB.NET文件對象的相關(guān)操作技巧就為大家介紹到這里。
【編輯推薦】