動態編輯CSV文件的內容我有這樣的代碼使用VB.net
Dim fileReader As System.IO.StreamReader
fileReader =
My.Computer.FileSystem.OpenTextFileReader("Filepath")
Dim stringReader As String
'read csv file from first to last line
While fileReader.ReadLine <> ""
'get data of line
stringReader = fileReader.ReadLine()
'check the number of commas in the line
Dim meh As String() = stringReader.Split(",")
If meh.Length > 14 Then
My.Computer.FileSystem.WriteAllText("Filepath", "asd", True)
ElseIf meh.Length < 14 Then
My.Computer.FileSystem.WriteAllText("Filepath", "asd", True)
ElseIf meh.Length = 14 Then
MsgBox("This line of the file has " & stringReader & meh.Length & "commas")
End If
End While
End
End Sub
爲了解釋,上面的代碼會檢查CSV文件,檢查天氣內容的每一行都有14個逗號(') 。然後,如果該行有更多的逗號,則代碼會將其減少到14,如果不是,則它將寫入逗號以便它等於14.上述條件尚未創建,因此代碼僅用於測試。我讀了一些關於WriteAllText這個代碼給我的錯誤:
The process cannot access the file 'filepath' because it is being used by another process.
其中,我認爲,這意味着,因爲我目前使用它的數據我不能編輯CSV文件。
我的問題是,即使在檢查其內容時,如何編輯CSV文件的內容?
請不要忽略此代碼
My.Computer.FileSystem.WriteAllText("Filepath", "asd", True)
,因爲我使用此代碼只是爲了測試,如果有的話我可以設法將其寫入到CSV文件。
我感謝您的幫助。
您無法寫入已打開的文件進行讀取。除非文件非常大,否則可以使用File.ReadAllLines()加載所有數據,以便關閉文件並寫入文件。它看起來就是那個applet所做的,但通常你會想要關閉和處理流 - 不這樣做可能會導致相同的錯誤;和'End'不是退出NET應用程序的好方法。 – Plutonix
對不起,'結束'@Plutonix我應該把它處理掉。你可能會建議什麼? –
如果它是一個Winforms應用程序,主窗體上的Me.Close會結束它 – Plutonix