简体   繁体   English

加载文本文件以快速访问C#Windows Form应用程序

[英]loading a text file for quick access C# windows form app

I couldn't find an answer to this on the other stackoverflow is I'll ask it here. 我在另一个stackoverflow上找不到答案,这是我会在这里问的。 I have a text file with roughly 100000 rows. 我有一个大约100000行的文本文件。 I have been doing multiple queries on it such as this 我一直在做这样的多个查询

string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = @"SELECT Count(*) as NumberofRecords FROM [" + fileName + "]";

using (OleDbConnection connection = new OleDbConnection(
       @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
       ";Extended Properties=\"Text;HDR=" + header + "\""))
using (OleDbCommand command = new OleDbCommand(sql, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
    DataTable dt = new DataTable();
    dt.Locale = CultureInfo.CurrentCulture;
    adapter.Fill(dt);
    return dt;
}

And it is doing multiple versions of this. 它正在做这个的多个版本。 Is there any way to load the textfile so that I can run things like this faster? 有什么方法可以加载文本文件,以便我可以更快地运行此类文件? Is there a better way? 有没有更好的办法? Currently it is taking too long. 目前花费的时间太长。

What are you trying to do? 你想做什么?

From your sample it looks like the only thing you're trying to do is to get the number of records in the file. 从您的样本中看来,您想要做的唯一一件事就是获取文件中的记录数。

You might be safe to instead just count the number of lines (-1 line for the header) iff* you don't have content that spans multiple lines. 如果您没有跨多行的内容,则可以安全地仅对行数(标题为-1行)进行计数。

* if, and only if * 当且仅当

EDIT: 编辑:

So counting the number of lines is not an option since you're doing more complicated stuff. 因此,计算行数不是一种选择,因为您正在做更复杂的事情。

I just generated a sample file with 100k records (7.7 MB in size) which got processed in 0.43 seconds. 我刚刚生成了一个具有10万条记录(大小为7.7 MB)的示例文件,该文件在0.43秒内得到了处理。 Doing a count(*) .. group by Name took 0.58 seconds. count(*) .. group by Name进行count(*) .. group by Name需要0.58秒。

What are your numbers and why do you think it's taking too long? 您的电话号码是什么,为什么您认为花费的时间太长? Where does the file lie? 文件在哪里? Is it perhaps a network/slow drive issue? 可能是网络/慢速驱动器问题?

Load the file into memory using a stream, See here . 使用流将文件加载到内存中,请参见此处 Once it's in memory, run your queries etc. 一旦它在内存中,运行您的查询等。

You can use the the following example: 您可以使用以下示例:

string filename = @"C:\BigTextFile.txt";  
StreamReader sr = System.IO.File.OpenText(filename);

// Process line by line.  
string line = "";  
do  
{  
line = sr.ReadLine();  
}  
while(sr.Peek() != -1);  

// Load all at once and process.  
string alltext = sr.ReadToEnd();  

sr.Close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM