文件处理在C#.NET [英] file handling in c# .net

查看:136
本文介绍了文件处理在C#.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有事情我想做的事情的清单。我有一个窗体应用程序。

There is a list of things i want to do. I have a forms application.

1)进入一个特定的行。我知道如何去以串行方式,但有什么办法通过它我可以跳转到一个特定的行号

1) Go to a particular line. I know how to go in a serial manner, but is there any way by which i can jump to a particular line no.

2)要找出不共线

推荐答案

如果文件不是太大,可以尝试的 ReadAllLines

If the file is not too big, you can try the ReadAllLines.

这读取整个文件到一个字符串数组,其中每行是数组的元素。

This reads the whole file, into a string array, where every line is an element of the array.

例如:

var fileName = @"C:\MyFolder\MyFileName.txt";
var contents = System.IO.File.ReadAllLines(fileName);

Console.WriteLine("Line: 10: " + contents[9]);
Console.WriteLine("Number of lines:");
Console.WriteLine(contents.Lenght);

但要注意:此读取整个文件到内存

如果该文件是太大了:

打开文件( OpenText的),并创建一个字典来每行的存储偏移。扫描的每一行,并存储偏移量。现在,你可以去到每一行,你有行数。

Open the file (OpenText), and create a Dictionary to store the offset of every line. Scan every line, and store the offset. Now you can go to every line, and you have the number of lines.

var lineOffset = new Dictionary<int, long>();
using (var rdr = System.IO.File.OpenText(fileName)) {
   int lineNr = 0;
   lineOffset.Add(0,0);
   while (rdr.ReadLine() != null)) {
       lineNr++;
       lineOffset.Add(lineNr, rdr.BaseStream.Position);
   }

   // Goto line 10
   rdr.BaseStream.Position = lineOffset[10];
   var line10 = rdr.ReadLine();
}

这篇关于文件处理在C#.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆