首页 > 代码库 > c#读取大Txt文件
c#读取大Txt文件
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;namespace ReadBigTxtDemo{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnRead_Click(object sender, EventArgs e) { if (ReadBigFile()) { lblResult.Text = "Completed!"; } } private bool ReadBigFile() { string sTmpFile=@"c:\tmpTest.txt"; if (File.Exists(sTmpFile)) { File.Delete(sTmpFile); } if (!System.IO.File.Exists(sTmpFile)) { FileStream fs; fs = File.Create(sTmpFile); fs.Close(); } if (!File.Exists(txtFileName.Text.Trim())) { lblResult.Text = "File not exist!"; txtFileName.Focus(); return false; } FileStream streamInput = System.IO.File.OpenRead(@txtFileName.Text.Trim()); FileStream streamOutput = System.IO.File.OpenWrite(sTmpFile); int iRowCount = 10; int.TryParse(txtRowCount.Text.Trim(), out iRowCount); try { for (int i = 1; i <= iRowCount; ) { int result = streamInput.ReadByte(); if (result == 13) { i++; } if (result == -1) { break; } streamOutput.WriteByte((byte)result); } } finally { streamInput.Dispose(); streamOutput.Dispose(); } string sContent = ReaderFile(sTmpFile); CopyToClipboard(sContent); return true; } public static string ReaderFile(string path) { string fileData = http://www.mamicode.com/string.Empty; try { ///读取文件的内容 StreamReader reader = new StreamReader(path, Encoding.Default); fileData = reader.ReadToEnd(); reader.Close(); } catch (Exception ex) { // throw new Exception(ex.Message,ex); } ///抛出异常 return fileData; } private void CopyToClipboard(string sSource) { Clipboard.Clear(); if (!string.IsNullOrEmpty(sSource)) { Clipboard.SetText(sSource); } } }}
窗体
c#读取大Txt文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。