Pages

2009年11月13日 星期五

逐行讀取做判斷

讀取的資料為cvs檔,內有多行資料

想一次讀取一行做判斷
如果不包含指定的字串刪除該行資料
如果包含指定字串則刪除該字串但保留該行其他資料
想請教語法該如何寫才能做到逐行判斷

以下為程式碼
Dim filename As String
Dim sr As StreamReader
Dim sw As StreamWriter
Dim line As String
Dim num As New Integer
Dim newfile As String
Dim newline As String

filename = Console.ReadLine

sr = New StreamReader(filename)
newfile = filename.Replace(".txt", ".cvs")
sw = New StreamWriter(newfile)

Do

   line = sr.ReadLine()
   num = line.IndexOf("(N)")

   If num > -1 Then
      newline = line.Remove(num, 3)
      sw.WriteLine(newline)
   Else

   End If
Loop Until line Is Nothing

sr.Close()
sw.Close()



在 num = line.IndexOf("(N)")這一行出現
"並未將物件參考設定為物件的執行個體"
num這變數已經用new宣告了
line讀進來的值為null時迴圈也應該停止了才對



解答:
While sr.Peek > -1
先檢查是不是讀到尾了再去做readLine

沒有留言:

張貼留言