2011-10-21 34 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

编辑,,,现在检查家伙 –

相关问题