1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
|
// LumenWorks.Framework.IO.CSV.CachedCsvReader
// Copyright (c) 2005 Sbastien Lorion
//
// MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using LumenWorks.Framework.IO.Csv.Resources;
namespace LumenWorks.Framework.IO.Csv
{
/// <summary>
/// Represents a reader that provides fast, cached, dynamic access to CSV data.
/// </summary>
/// <remarks>The number of records is limited to <see cref="System.Int32.MaxValue"/> - 1.</remarks>
public partial class CachedCsvReader
: CsvReader, IListSource
{
#region Fields
/// <summary>
/// Contains the cached records.
/// </summary>
private List<string[]> _records;
/// <summary>
/// Contains the current record index (inside the cached records array).
/// </summary>
private long _currentRecordIndex;
/// <summary>
/// Indicates if a new record is being read from the CSV stream.
/// </summary>
private bool _readingStream;
/// <summary>
/// Contains the binding list linked to this reader.
/// </summary>
private CsvBindingList _bindingList;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the CsvReader class.
/// </summary>
/// <param name="reader">A <see cref="T:TextReader"/> pointing to the CSV file.</param>
/// <param name="hasHeaders"><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="reader"/> is a <see langword="null"/>.
/// </exception>
/// <exception cref="T:ArgumentException">
/// Cannot read from <paramref name="reader"/>.
/// </exception>
public CachedCsvReader(TextReader reader, bool hasHeaders)
: this(reader, hasHeaders, DefaultBufferSize)
{
}
/// <summary>
/// Initializes a new instance of the CsvReader class.
/// </summary>
/// <param name="reader">A <see cref="T:TextReader"/> pointing to the CSV file.</param>
/// <param name="hasHeaders"><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</param>
/// <param name="bufferSize">The buffer size in bytes.</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="reader"/> is a <see langword="null"/>.
/// </exception>
/// <exception cref="T:ArgumentException">
/// Cannot read from <paramref name="reader"/>.
/// </exception>
public CachedCsvReader(TextReader reader, bool hasHeaders, int bufferSize)
: this(reader, hasHeaders, DefaultDelimiter, DefaultQuote, DefaultEscape, DefaultComment, true, bufferSize)
{
}
/// <summary>
/// Initializes a new instance of the CsvReader class.
/// </summary>
/// <param name="reader">A <see cref="T:TextReader"/> pointing to the CSV file.</param>
/// <param name="hasHeaders"><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</param>
/// <param name="delimiter">The delimiter character separating each field (default is ',').</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="reader"/> is a <see langword="null"/>.
/// </exception>
/// <exception cref="T:ArgumentException">
/// Cannot read from <paramref name="reader"/>.
/// </exception>
public CachedCsvReader(TextReader reader, bool hasHeaders, char delimiter)
: this(reader, hasHeaders, delimiter, DefaultQuote, DefaultEscape, DefaultComment, true, DefaultBufferSize)
{
}
/// <summary>
/// Initializes a new instance of the CsvReader class.
/// </summary>
/// <param name="reader">A <see cref="T:TextReader"/> pointing to the CSV file.</param>
/// <param name="hasHeaders"><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</param>
/// <param name="delimiter">The delimiter character separating each field (default is ',').</param>
/// <param name="bufferSize">The buffer size in bytes.</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="reader"/> is a <see langword="null"/>.
/// </exception>
/// <exception cref="T:ArgumentException">
/// Cannot read from <paramref name="reader"/>.
/// </exception>
public CachedCsvReader(TextReader reader, bool hasHeaders, char delimiter, int bufferSize)
: this(reader, hasHeaders, delimiter, DefaultQuote, DefaultEscape, DefaultComment, true, bufferSize)
{
}
/// <summary>
/// Initializes a new instance of the CsvReader class.
/// </summary>
/// <param name="reader">A <see cref="T:TextReader"/> pointing to the CSV file.</param>
/// <param name="hasHeaders"><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</param>
/// <param name="delimiter">The delimiter character separating each field (default is ',').</param>
/// <param name="quote">The quotation character wrapping every field (default is ''').</param>
/// <param name="escape">
/// The escape character letting insert quotation characters inside a quoted field (default is '\').
/// If no escape character, set to '\0' to gain some performance.
/// </param>
/// <param name="comment">The comment character indicating that a line is commented out (default is '#').</param>
/// <param name="trimSpaces"><see langword="true"/> if spaces at the start and end of a field are trimmed, otherwise, <see langword="false"/>. Default is <see langword="true"/>.</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="reader"/> is a <see langword="null"/>.
/// </exception>
/// <exception cref="T:ArgumentException">
/// Cannot read from <paramref name="reader"/>.
/// </exception>
public CachedCsvReader(TextReader reader, bool hasHeaders, char delimiter, char quote, char escape, char comment, bool trimSpaces)
: this(reader, hasHeaders, delimiter, quote, escape, comment, trimSpaces, DefaultBufferSize)
{
}
/// <summary>
/// Initializes a new instance of the CsvReader class.
/// </summary>
/// <param name="reader">A <see cref="T:TextReader"/> pointing to the CSV file.</param>
/// <param name="hasHeaders"><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</param>
/// <param name="delimiter">The delimiter character separating each field (default is ',').</param>
/// <param name="quote">The quotation character wrapping every field (default is ''').</param>
/// <param name="escape">
/// The escape character letting insert quotation characters inside a quoted field (default is '\').
/// If no escape character, set to '\0' to gain some performance.
/// </param>
/// <param name="comment">The comment character indicating that a line is commented out (default is '#').</param>
/// <param name="trimSpaces"><see langword="true"/> if spaces at the start and end of a field are trimmed, otherwise, <see langword="false"/>. Default is <see langword="true"/>.</param>
/// <param name="bufferSize">The buffer size in bytes.</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="reader"/> is a <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="bufferSize"/> must be 1 or more.
/// </exception>
public CachedCsvReader(TextReader reader, bool hasHeaders, char delimiter, char quote, char escape, char comment, bool trimSpaces, int bufferSize)
: base(reader, hasHeaders, delimiter, quote, escape, comment, trimSpaces, bufferSize)
{
_records = new List<string[]>();
_currentRecordIndex = -1;
}
#endregion
#region Properties
#region State
/// <summary>
/// Gets the current record index in the CSV file.
/// </summary>
/// <value>The current record index in the CSV file.</value>
public override long CurrentRecordIndex
{
get
{
return _currentRecordIndex;
}
}
/// <summary>
/// Gets a value that indicates whether the current stream position is at the end of the stream.
/// </summary>
/// <value><see langword="true"/> if the current stream position is at the end of the stream; otherwise <see langword="false"/>.</value>
public override bool EndOfStream
{
get
{
if (_currentRecordIndex < base.CurrentRecordIndex)
return false;
else
return base.EndOfStream;
}
}
#endregion
#endregion
#region Indexers
/// <summary>
/// Gets the field at the specified index.
/// </summary>
/// <value>The field at the specified index.</value>
/// <exception cref="T:ArgumentOutOfRangeException">
/// <paramref name="field"/> must be included in [0, <see cref="M:FieldCount"/>[.
/// </exception>
/// <exception cref="T:InvalidOperationException">
/// No record read yet. Call ReadLine() first.
/// </exception>
/// <exception cref="MissingFieldCsvException">
/// The CSV data appears to be missing a field.
/// </exception>
/// <exception cref="T:MalformedCsvException">
/// The CSV appears to be corrupt at the current position.
/// </exception>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
public override String this[int field]
{
get
{
if (_readingStream)
return base[field];
else if (_currentRecordIndex > -1)
{
if (field > -1 && field < this.FieldCount)
return _records[(int) _currentRecordIndex][field];
else
throw new ArgumentOutOfRangeException("field", field, string.Format(CultureInfo.InvariantCulture, ExceptionMessage.FieldIndexOutOfRange, field));
}
else
throw new InvalidOperationException(ExceptionMessage.NoCurrentRecord);
}
}
#endregion
#region Methods
#region Read
/// <summary>
/// Reads the CSV stream from the current position to the end of the stream.
/// </summary>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
public virtual void ReadToEnd()
{
_currentRecordIndex = base.CurrentRecordIndex;
while (ReadNextRecord()) ;
}
/// <summary>
/// Reads the next record.
/// </summary>
/// <param name="onlyReadHeaders">
/// Indicates if the reader will proceed to the next record after having read headers.
/// <see langword="true"/> if it stops after having read headers; otherwise, <see langword="false"/>.
/// </param>
/// <param name="skipToNextLine">
/// Indicates if the reader will skip directly to the next line without parsing the current one.
/// To be used when an error occurs.
/// </param>
/// <returns><see langword="true"/> if a record has been successfully reads; otherwise, <see langword="false"/>.</returns>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
protected override bool ReadNextRecord(bool onlyReadHeaders, bool skipToNextLine)
{
if (_currentRecordIndex < base.CurrentRecordIndex)
{
_currentRecordIndex++;
return true;
}
else
{
_readingStream = true;
try
{
bool canRead = base.ReadNextRecord(onlyReadHeaders, skipToNextLine);
if (canRead)
{
string[] record = new string[this.FieldCount];
if (base.CurrentRecordIndex > -1)
{
CopyCurrentRecordTo(record);
_records.Add(record);
}
else
{
MoveTo(0);
CopyCurrentRecordTo(record);
MoveTo(-1);
}
if (!onlyReadHeaders)
_currentRecordIndex++;
}
else
{
// No more records to read, so set array size to only what is needed
_records.Capacity = _records.Count;
}
return canRead;
}
finally
{
_readingStream = false;
}
}
}
#endregion
#region Move
/// <summary>
/// Moves before the first record.
/// </summary>
public void MoveToStart()
{
_currentRecordIndex = -1;
}
/// <summary>
/// Moves to the last record read so far.
/// </summary>
public void MoveToLastCachedRecord()
{
_currentRecordIndex = base.CurrentRecordIndex;
}
/// <summary>
/// Moves to the specified record index.
/// </summary>
/// <param name="record">The record index.</param>
/// <exception cref="T:ArgumentOutOfRangeException">
/// Record index must be > 0.
/// </exception>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
public override void MoveTo(long record)
{
if (record < -1)
throw new ArgumentOutOfRangeException("record", record, ExceptionMessage.RecordIndexLessThanZero);
if (record <= base.CurrentRecordIndex)
_currentRecordIndex = record;
else
{
_currentRecordIndex = base.CurrentRecordIndex;
long offset = record - _currentRecordIndex;
// read to the last record before the one we want
while (offset-- > 0 && ReadNextRecord()) ;
}
}
#endregion
#endregion
#region IListSource Members
bool IListSource.ContainsListCollection
{
get { return false; }
}
System.Collections.IList IListSource.GetList()
{
if (_bindingList == null)
_bindingList = new CsvBindingList(this);
return _bindingList;
}
#endregion
}
}
|