首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C# 使用 StreamReader 讀取文本文件最後三列數據並綁定到 ListView 控件

     編輯:程式設計疑難解答

核心代碼


public void LoadLastThreeColumns(string filePath, ListView listView) {
    listView.Items.Clear();
    listView.View = View.Details;
    listView.Columns.Add("倒數第3列", 100);
    listView.Columns.Add("倒數第2列", 100);
    listView.Columns.Add("最後一列", 100);

    using (StreamReader sr = new StreamReader(filePath, Encoding.Default)) {
        string line;
        while ((line = sr.ReadLine()) != null) {
            string[] cols = line.Split(new char[] {' ', '\t', ','}, StringSplitOptions.RemoveEmptyEntries);
            if (cols.Length >= 3) {
                // 取最後三列
                string[] lastThree = new string[3];
                Array.Copy(cols, cols.Length - 3, lastThree, 0, 3);
                ListViewItem item = new ListViewItem(lastThree);
                listView.Items.Add(item);
            }
        }
    }
}

關鍵點

  • StreamReader 逐行讀取,內存占用恆定,適合大文件。
  • Split 支持多種分隔符(空格、制表符、逗號),RemoveEmptyEntries 去除空列。
  • Array.Copy 高效提取尾部三列,避免手動索引易出錯。
  • ListView.View = View.Details 顯示表格模式。

異步版本(防止 UI 卡頓)


public async Task LoadLastThreeColumnsAsync(string filePath, ListView listView) {
    listView.Items.Clear();
    // ... 初始化 Columns
    using (StreamReader sr = new StreamReader(filePath, Encoding.Default)) {
        string line;
        var items = new List();
        while ((line = await sr.ReadLineAsync()) != null) {
            string[] cols = line.Split(new char[] {' ', '\t', ','}, StringSplitOptions.RemoveEmptyEntries);
            if (cols.Length >= 3) {
                string[] lastThree = new string[3];
                Array.Copy(cols, cols.Length - 3, lastThree, 0, 3);
                items.Add(new ListViewItem(lastThree));
            }
        }
        listView.Items.AddRange(items.ToArray());
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved