用VB讀寫文字檔的簡單函式

以下是我常用的VB檔案讀寫函式,我自己覺得還滿方便的

程式碼

丟給它路徑與new好的ArrayList就可以讀檔了,讀出來後ArrayList中會都是String,每個String代表一行,寫入也是反向動作,如果寫入的路徑不存在會自己產生目錄

修改encoding就可以設定寫入的編碼,預設用UTF8

Imports System.IO
Public Class MyFileIO
Public encoding As System.Text.Encoding = System.Text.Encoding.UTF8

Public Sub fileReadLine(ByRef path As String, ByRef fileData As ArrayList)
    If Not fileData Is Nothing And Not path.Equals("") And System.IO.File.Exists(path) Then
        Dim readfile As New System.IO.StreamReader(path, encoding)
        Dim str As String
        str = readfile.ReadLine()
        While Not str Is Nothing
            fileData.Add(str)
            str = readfile.ReadLine
        End While
        readfile.Close()
    End If
End Sub

Public Sub fileWriteLine(ByRef path As String, ByRef fileData As ArrayList)
    If Not fileData Is Nothing And Not path.Equals("") Then
        Directory.CreateDirectory(path.Substring(0, path.LastIndexOf("\")))
        Dim writefile As New System.IO.StreamWriter(path, False, encoding)
        Dim i As Integer
        Dim str As String
        For i = 0 To fileData.Count - 1
            str = fileData.Item(i)
            writefile.WriteLine(str)
        Next
        writefile.Close()
    End If
End Sub
End Class

相關

如果要取得應用程式所在路徑可用:

 Dim path as String = System.Windows.Forms.Application.StartupPath + "\"

如果是Web App的話則使用

 Dim path As String = Server.MapPath("~/")

相關連結

0 意見:

這裡是關於技術的手札~

也歡迎大家到

倫與貓的足跡



到噗浪來

關心一下我唷!
by 倫
 
Copyright 2009 倫倫3號Beta-Log All rights reserved.
Blogger Templates created by Deluxe Templates
Wordpress Theme by EZwpthemes