2011-10-21 37 views
3

在VB6中,如果該行包含某些字符串,我正在尋找一種從文本文件中刪除一行文本的方法。我主要與C#一起工作,在這裏我很茫然。使用.NET有幾種方法可以做到這一點,但我很幸運,必須維護一些舊的VB代碼。如果該行包含一些字符串,則從文本文件中刪除一行

有沒有辦法做到這一點?

感謝

回答

5

假設你有文件名中的變量sFileName

Dim iFile as Integer 
Dim sLine as String, sNewText as string 

iFile = FreeFile 

Open sFileName For Input As #iFile 
Do While Not EOF(iFile) 
    Line Input #iFile, sLine 
    If sLine Like "*foo*" Then 
    ' skip the line 
    Else 
    sNewText = sNewText & sLine & vbCrLf 
    End If 
Loop 
Close 

iFile = FreeFile 
Open sFileName For Output As #iFile 
Print #iFile, sNewText 
Close 

您可能要輸出到不同的文件,而不是覆蓋源文件,但希望這讓你更接近。

+0

謝謝你的幫忙! – JimDel

4

好文本文件來自某些角度來看一個複雜的野獸:你不能刪除線和向後移動進一步文本,它是一個流。

我建議你約,而不是考慮的輸入輸出方式:

1)打開輸入文件爲文本

2)打開用於輸出的第二個文件,臨時文件。

3)你通過文件A.

4)如果當前行包含我們的字符串,不寫它的所有行迭代。如果當前行沒有 包含我們的字符串,我們把它寫在文件B.

5)你關閉文件A,你關閉文件B.

現在你可以添加一些步驟。

6)刪除文件中的一個文件的位置的

7)移動文件B。

-3
DeleteLine "C:\file.txt", "John Doe", 0, 
Function DeleteLine(strFile, strKey, LineNumber, CheckCase) 

'Use strFile = "c:\file.txt" (Full path to text file) 
'Use strKey = "John Doe"  (Lines containing this text string to be deleted) 

    Const ForReading = 1 
    Const ForWriting = 2 

    Dim objFSO, objFile, Count, strLine, strLineCase, strNewFile 

    Set objFSO = CreateObject("Scripting.FileSystemObject")  
    Set objFile = objFSO.OpenTextFile(strFile, ForReading) 

    Do Until objFile.AtEndOfStream 
     strLine = objFile.Readline 

     If CheckCase = 0 Then strLineCase = UCase(strLine): strKey = UCase(strKey) 
     If LineNumber = objFile.Line - 1 Or LineNumber = 0 Then 
      If InStr(strLine, strKey) Or InStr(strLineCase, strKey) Or strKey = "" Then 
      strNewFile = strNewFile 
      Else 
      strNewFile = strNewFile & strLine & vbCrLf 
      End If 
     Else 
      strNewFile = strNewFile & strLine & vbCrLf 
     End If 

    Loop 
    objFile.Close 

    Set objFSO = CreateObject("Scripting.FileSystemObject") 
    Set objFile = objFSO.OpenTextFile(strFile, ForWriting) 

    objFile.Write strNewFile 
    objFile.Close 
End Function 
+0

請至少添加評論,並確保你的答案增加了現有的一些價值 – mikus

+0

其通常認爲很好的解釋代碼也只給代碼答案可能不會對未來的讀者有幫助 –

+0

編輯,,,現在檢查傢伙 –

相關問題