2012-06-25 77 views
-1

我想从html源代码读取特定行。 林存储源到一个字符串文件,我想读的线X 所以使用这种方法,我在网上阅读特定行

Public Shared Function ReadSpecifiedLine(file As String, lineNum As Integer) As String 
    Dim contents As String = String.Empty 
    Try 
     Using stream As New StreamReader(file) 
      contents = stream.ReadToEnd() 
      Dim linesArray As String() = contents.Split(New Char() {ControlChars.Lf}) 

      If linesArray.Length > 1 Then 
       If Not lineNum > linesArray.Length AndAlso Not lineNum < 0 Then 
        Return linesArray(lineNum) 
       Else 
        Return linesArray(0) 
       End If 
      Else 
       Return contents 
      End If 
     End Using 
    Catch ex As Exception 
     Return ex.ToString() 
    End Try 
End Function 

发现例如我尝试读取4号线和即时得到这个错误即时通讯。

System.ArgumentException:路径中的非法字符。 (字符串路径,布尔检查附加) at System.IO.Path.GetFileName(String path) at System.IO.StreamReader..ctor(String path,Encoding encoding,Boolean detectEncodingFromByteOrderMarks,Int32 BUFFERSIZE,布尔checkHost) 在System.IO.StreamReader..ctor(字符串路径) 在WindowsApplication1.Form1.ReadSpecifiedLine(字符串文件,的Int32 LINENUM)在C:\ Users \用户的Optimus \文件\视觉工作室2012 \项目\ WindowsApplication1 \ WindowsApplication1 \ Form1.vb:line 48

任何帮助,将不胜感激。

+0

什么是'file'参数传递当值该方法失败? – Steve

+0

你是否在文件参数中传递文件的路径?或者或者你传递文件的实际内容? – Jason

回答

1

您发布的方法假定您正在传入文件路径。如果你想改变它,接受实际的文件内容,而不是文件路径,你可以通过摆脱流对象的简化方法:

Public Shared Function ReadSpecifiedLine(contents As String, lineNum As Integer) As String 
    Dim linesArray As String() = contents.Split(New Char() {ControlChars.Lf}) 
    If linesArray.Length > 1 Then 
     If Not lineNum > linesArray.Length AndAlso Not lineNum < 0 Then 
      Return linesArray(lineNum) 
     Else 
      Return linesArray(0) 
     End If 
    Else 
     Return contents 
    End If 
End Function 
+0

非常感谢它现在的工作 – Incognito

0

看起来您正在传递文件的内容而不是文件的路径。

看到您用来调用此函数的代码而非此函数本身会很有用。

+0

我在这里叫它 TextBox5.Text = ReadSpecifiedLine(sourcecode,4) – Incognito

+0

但是'sourcecode'是文件的名字还是文件的内容? – Steve

+0

是的,你的线条类似于 sourecode =“?????” – goughy000