我使用c#.net开发了一个文件读取例程,它将使用合适的数据类或结构将整个文件内容读入内存。
我有一个600MB的文本文件,其中包含RoadId和许多其他条目。我必须使用查询方法读取该文件,因此我在c#.net中使用了Stream Reader,它逐行读取。但是我想知道c#.net中是否有任何其他方法可以节省内存,减少时间或将文本转换为二进制然后再读取。
不确定请引导我完成此事。
我正在逐行读取整个文件的代码......
public static void read_time()
{
DateTime end;
StreamReader file =
new StreamReader(@"C:\Users\Reva-Asus1\Desktop\DTF Test\F_Network_out.txt");
DateTime start = DateTime.Now;
while ((file.ReadLine()) != null) ;
end = DateTime.Now;
Console.WriteLine();
Console.WriteLine("Full File Read Time: " + (end - start));
Console.WriteLine();
file.Close();
Console.WriteLine("Data is read");
Console.ReadLine();
return;
}
//这个查询方法是从用户的控制台获取roadId并显示记录....
public static void querying_method()
{
Console.WriteLine("Give a RoadId to search record\n");
DateTime start, end;
string id =Console.ReadLine().Trim();
try
{
System.IO.StreamReader file =
new System.IO.StreamReader(@"C:\Users\Reva-Asus1\Desktop\DTF Test\F_Network_out.txt");
string line1;
int count = 1;
start = DateTime.Now;
while ((line1 = file.ReadLine()) != null)
{
if(line1 == id)
{
string line2 = " ";
while (count != 14)
{
Console.WriteLine(line2 = file.ReadLine());
count++;
}
int n = Convert.ToInt16(line2);
while (n != 0)
{
Console.WriteLine(line2 = file.ReadLine());
n--;
}
break;
}
}
end = DateTime.Now;
Console.WriteLine("Read Time for the data record: " + (end - start));
Console.ReadLine();
return;
}
catch (Exception)
{
Console.WriteLine("No ID match found in the file entered by user");
Console.ReadLine();
return;
}
}
答案 0 :(得分:1)
你可以使用它:
foreach (var line in File.ReadLines(path))
{
// TODO: Parse the line and convert to your object...
}
答案 1 :(得分:0)
File.ReadLines(YourPath)
正在后台使用StreamReader,因此您可以继续使用它。这里reference code。因此,如果您已经使用StreamReader
和只能阅读一行,那么您就不需要更改任何内容。
using (StreamReader sr = new StreamReader(path, encoding))
{
while ((line = sr.ReadLine()) != null)
{
//You are reading the file line by line and you load only the current line in the memory, not the whole file.
//do stuff which you want with the current line.
}
}