طريقة فعالة لقراءة علامة تبويب كبيرة ملف TXT محدد؟

StackOverflow https://stackoverflow.com/questions/6051275

  •  15-11-2019
  •  | 
  •  

سؤال

لدي ملف txt محدد علامة التبويب مع سجلات 500K.أنا أستخدم الرمز أدناه لقراءة البيانات إلى DataSet.مع 50K يعمل بشكل جيد ولكن 500K يعطي "استثناء من النوع" System.OutofMemoryException "تم إلقاؤه."

ما هي الطريقة الأكثر كفاءة لقراءة البيانات المحددة علامة التبويب الكبيرة؟ أو كيفية حل هذه المشكلة؟من فضلك أعطني مثال giveacodicetagpre.

هل كانت مفيدة؟

المحلول

Use a stream approach with TextFieldParser - this way you will not load the whole file into memory in one go.

نصائح أخرى

You really want to enumerate the source file and process each line at a time. I use the following

    public static IEnumerable<string> EnumerateLines(this FileInfo file)
    {
        using (var stream = File.Open(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (var reader = new StreamReader(stream))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }

Then for each line you can split it using tabs and process each line at a time. This keeps memory down really low for the parsing, you only use memory if the application needs it.

Have you tried the TextReader?

  using (TextReader tr = File.OpenText(YourFile))
  {
      string strLine = string.Empty;
      string[] arrColumns = null;
      while ((strLine = tr.ReadLine()) != null)
      {
           arrColumns = strLine .Split('\t');
           // Start Fill Your DataSet or Whatever you wanna do with your data
      }
      tr.Close();
  }

I found FileHelpers

The FileHelpers are a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.

Maybe it can help.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top