C 高效提取txt文件最後一行資料

2021-09-24 05:53:44 字數 1918 閱讀 4150

anuof 關注

如題,最近在開發乙個小型專案,由於資料量比較小,且無複雜的資料關係,資料量一天乙個物件大概也就2~3m的大小,所以就將資料寫入txt文件進行儲存,如下圖所示:

每一天的資料

6-23的資料

但在最後查詢一整天的歷史資料的時候,每一條資料的開始時間和結束時間分別是對應txt文件的第一行和最後一行資料裡面的時間,所以在查詢歷史資料的時候,需要讀取每乙個txt檔案中的第乙個和最後一行,最開始我的提取方法如下:

using (filestream fs = new filestream(filename, filemode.open, fileaccess.read, fileshare.readwrite))

using (streamreader sr = new streamreader(fs))

info.starttime = convert.todatetime(data.timestamp);

// 讀取末行

while (!sr.endofstream)

....

sr.close();

fs.close();

}

在整合到系統時,由於某一天的歷史資料大概有1000多條,所以在查詢時耗時很長,長到無法忍受,看了下**,應該是提取最後一行資料時花費較多時間,所以就優化了下**,如所示:

using (filestream fs = new filestream(filename, filemode.open, fileaccess.read, fileshare.readwrite))

using (streamreader sr = new streamreader(fs))

info.starttime = convert.todatetime(data.timestamp);

// 讀取末行

line = getlastline(fs);

...sr.close();

fs.close();

讀取最後一行資料的方法如下:

/// /// 提取文字最後一行資料

///

/// 檔案流

/// 最後一行資料

private string getlastline(filestream fs)

, stringsplitoptions.removeemptyentries);

string line = lines[lines.length - 1];

return line;

}

優化後的查詢耗時也就1 ~ 2秒就完成,比起之前真是快了不是一丟丟啊~

所以同志們,方法是多麼重要哦。

另外,在同時讀寫同乙個檔案時,需要設定檔案流的fileshare.readwrite

寫檔案 using (streamwriter sw = new streamwriter(fs))

讀檔案

using (filestream fs = new filestream(filename, filemode.open, fileaccess.read, fileshare.readwrite))

using (streamreader sr = new streamreader(fs))

讚賞支

C 高效提取txt文件最後一行資料

關注如題,最近在開發乙個小型專案,由於資料量比較小,且無複雜的資料關係,資料量一天乙個物件大概也就2 3m的大小,所以就將資料寫入txt文件進行儲存,如下圖所示 每一天的資料 6 23的資料 但在最後查詢一整天的歷史資料的時候,每一條資料的開始時間和結束時間分別是對應txt文件的第一行和最後一行資料...

C 讀取excel最後一行資料

如何讀取excel檔案 csv檔案的最後一行資訊,查閱網上各種資料,有直接操作excel表的 c 讀取excel檔案的三種經典方法 但這不是我想要的 讀取txt檔案的最後一行內容,有兩種思路 1.先讀取檔案的總行數,再獲取最後一行的內容,這種方法很簡潔,但是存在問題是當檔案資料量很龐大,比如有上萬行...

php刪除txt檔案最後一行

刪除檔案最後一行 param file path 檔案路徑 public function dellastline file path array pop content fclose file 重新寫入檔案 file fopen file path w fwrite file implode co...