程式開發筆記簿 program.maomo.info
從檔案取出特定資料行
以下的範例會逐行地讀入一個檔案,直到取得需要的那一行為止;這個檔案會被開啟在一個StreamReader中,當檔案逐行讀取時,自訂一個計數器來紀錄資料行的數量,一旦找到所指定的那一行,就把內容取出並傳回。

[VB.NET]
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
     '在這裡放置使用者程式碼以初始化網頁
     Dim FilePath As String = "F:\Uploads\test.txt"
     Response.Write(Me.GetLine(FilePath, 6))
End Sub 
'取出特定列數的資料行
Private Function GetLine(ByVal FilePath As String, _
ByVal LineNo As Integer) As String
     Dim strResult As String = ""
     Dim strTmp As String = ""
     Dim objSR As StreamReader = Nothing
     Dim intLine As Integer = 0

    Try
         objSR = File.OpenText(FilePath)
         strTmp = objSR.ReadLine()

         While Not strTmp Is Nothing
             intLine += 1

            If intLine = LineNo Then
                strResult = strTmp
                Exit While
            End If

            strTmp = objSR.ReadLine()
        End While

        If LineNo > intLine Then
            strResult = "輸入的資料行數大於檔案的資料行數"
        End If
    Catch ex As Exception
        strResult = ex.Message
    Finally
        objSR.Close()
    End Try

    Return strResult
End Function


[C#]
private void Page_Load(object sender, System.EventArgs e)
{
    // 在這裡放置使用者程式碼以初始化網頁
    string FilePath = "F:\\Uploads\\test.txt";
    Response.Write(this.GetLine(FilePath, 5));
} 
// 取出特定列數的資料行
private string GetLine(string FilePath , int LineNo)
{
    string strResult = "";
    string strTmp = "";
    StreamReader objSR = null;
    int intLine = 0;

    try
    {
        objSR = File.OpenText(FilePath);
        strTmp = objSR.ReadLine();

        while (strTmp != null)
        {
            intLine += 1;

            if (intLine == LineNo)
            {
                strResult = strTmp;
                goto exitWhile;
            }

            strTmp = objSR.ReadLine();
        }
        exitWhile:;

        if ( LineNo > intLine )
        {
            strResult = "輸入的資料行數大於檔案的資料行數";
        }
    }
    catch (Exception ex)
    {
        strResult = ex.Message;
    }
    finally
    {
        objSR.Close();
    }

    return strResult;
}
Edit: 2010/07/28 16:40:20   View: 412

1. ts   [ 2007/09/10 20:38:58]

雖然服務器在臺灣,不過速度非常的快

發表回應

大名:
E-Mail:
網址:
回應內容:
驗證碼:
回首頁 連絡阿毛 & 交流建議
© 2007-2010, 程式開發筆記簿 program.maomo.info
程式設計 & 網站建置: Vicky Chien 寄信給阿毛