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 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
|
// LumenWorks.Framework.IO.CSV.CsvReader
// 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;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using Debug = System.Diagnostics.Debug;
using System.Globalization;
using System.IO;
using LumenWorks.Framework.IO.Csv.Resources;
namespace LumenWorks.Framework.IO.Csv
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to CSV data.
/// </summary>
public partial class CsvReader
: IDataReader, IEnumerable<string[]>, IDisposable
{
#region Constants
/// <summary>
/// Defines the default buffer size.
/// </summary>
public const int DefaultBufferSize = 0x1000;
/// <summary>
/// Defines the default delimiter character separating each field.
/// </summary>
public const char DefaultDelimiter = ',';
/// <summary>
/// Defines the default quote character wrapping every field.
/// </summary>
public const char DefaultQuote = '"';
/// <summary>
/// Defines the default escape character letting insert quotation characters inside a quoted field.
/// </summary>
public const char DefaultEscape = '"';
/// <summary>
/// Defines the default comment character indicating that a line is commented out.
/// </summary>
public const char DefaultComment = '#';
#endregion
#region Fields
/// <summary>
/// Contains the field header comparer.
/// </summary>
private static readonly StringComparer _fieldHeaderComparer = StringComparer.CurrentCultureIgnoreCase;
#region Settings
/// <summary>
/// Contains the <see cref="T:TextReader"/> pointing to the CSV file.
/// </summary>
private TextReader _reader;
/// <summary>
/// Contains the buffer size.
/// </summary>
private int _bufferSize;
/// <summary>
/// Contains the comment character indicating that a line is commented out.
/// </summary>
private char _comment;
/// <summary>
/// Contains the escape character letting insert quotation characters inside a quoted field.
/// </summary>
private char _escape;
/// <summary>
/// Contains the delimiter character separating each field.
/// </summary>
private char _delimiter;
/// <summary>
/// Contains the quotation character wrapping every field.
/// </summary>
private char _quote;
/// <summary>
/// Indicates if spaces at the start and end of a field are trimmed.
/// </summary>
private bool _trimSpaces;
/// <summary>
/// Indicates if field names are located on the first non commented line.
/// </summary>
private bool _hasHeaders;
/// <summary>
/// Contains the default action to take when a parsing error has occured.
/// </summary>
private ParseErrorAction _defaultParseErrorAction;
/// <summary>
/// Contains the action to take when a field is missing.
/// </summary>
private MissingFieldAction _missingFieldAction;
/// <summary>
/// Indicates if the reader supports multiline.
/// </summary>
private bool _supportsMultiline;
/// <summary>
/// Indicates if the reader will skip empty lines.
/// </summary>
private bool _skipEmptyLines;
#endregion
#region State
/// <summary>
/// Indicates if the class is initialized.
/// </summary>
private bool _initialized;
/// <summary>
/// Contains the field headers.
/// </summary>
private string[] _fieldHeaders;
/// <summary>
/// Contains the dictionary of field indexes by header. The key is the field name and the value is its index.
/// </summary>
private Dictionary<string, int> _fieldHeaderIndexes;
/// <summary>
/// Contains the current record index in the CSV file.
/// A value of <see cref="M:Int32.MinValue"/> means that the reader has not been initialized yet.
/// Otherwise, a negative value means that no record has been read yet.
/// </summary>
private long _currentRecordIndex;
/// <summary>
/// Contains the starting position of the next unread field.
/// </summary>
private int _nextFieldStart;
/// <summary>
/// Contains the index of the next unread field.
/// </summary>
private int _nextFieldIndex;
/// <summary>
/// Contains the array of the field values for the current record.
/// A null value indicates that the field have not been parsed.
/// </summary>
private string[] _fields;
/// <summary>
/// Contains the maximum number of fields to retrieve for each record.
/// </summary>
private int _fieldCount;
/// <summary>
/// Contains the read buffer.
/// </summary>
private char[] _buffer;
/// <summary>
/// Contains the current read buffer length.
/// </summary>
private int _bufferLength;
/// <summary>
/// Indicates if the end of the reader has been reached.
/// </summary>
private bool _eof;
/// <summary>
/// Indicates if the last read operation reached an EOL character.
/// </summary>
private bool _eol;
/// <summary>
/// Indicates if the first record is in cache.
/// This can happen when initializing a reader with no headers
/// because one record must be read to get the field count automatically
/// </summary>
private bool _firstRecordInCache;
/// <summary>
/// Indicates if one or more field are missing for the current record.
/// Resets after each successful record read.
/// </summary>
private bool _missingFieldFlag;
/// <summary>
/// Indicates if a parse error occured for the current record.
/// Resets after each successful record read.
/// </summary>
private bool _parseErrorFlag;
#endregion
#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 CsvReader(TextReader reader, bool hasHeaders)
: this(reader, hasHeaders, DefaultDelimiter, 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="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 CsvReader(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 CsvReader(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 CsvReader(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 CsvReader(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 CsvReader(TextReader reader, bool hasHeaders, char delimiter, char quote, char escape, char comment, bool trimSpaces, int bufferSize)
{
#if DEBUG
_allocStack = new System.Diagnostics.StackTrace();
#endif
if (reader == null)
throw new ArgumentNullException("reader");
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException("bufferSize", bufferSize, ExceptionMessage.BufferSizeTooSmall);
_bufferSize = bufferSize;
if (reader is StreamReader)
{
Stream stream = ((StreamReader) reader).BaseStream;
if (stream.CanSeek)
{
// Handle bad implementations returning 0 or less
if (stream.Length > 0)
_bufferSize = (int) Math.Min(bufferSize, stream.Length);
}
}
_reader = reader;
_delimiter = delimiter;
_quote = quote;
_escape = escape;
_comment = comment;
_hasHeaders = hasHeaders;
_trimSpaces = trimSpaces;
_supportsMultiline = true;
_skipEmptyLines = true;
_currentRecordIndex = -1;
_defaultParseErrorAction = ParseErrorAction.RaiseEvent;
}
#endregion
#region Events
/// <summary>
/// Occurs when there is an error while parsing the CSV stream.
/// </summary>
public event EventHandler<ParseErrorEventArgs> ParseError;
/// <summary>
/// Raises the <see cref="M:ParseError"/> event.
/// </summary>
/// <param name="e">The <see cref="ParseErrorEventArgs"/> that contains the event data.</param>
protected virtual void OnParseError(ParseErrorEventArgs e)
{
EventHandler<ParseErrorEventArgs> handler = ParseError;
if (handler != null)
handler(this, e);
}
#endregion
#region Properties
#region Settings
/// <summary>
/// Gets the comment character indicating that a line is commented out.
/// </summary>
/// <value>The comment character indicating that a line is commented out.</value>
public char Comment
{
get
{
return _comment;
}
}
/// <summary>
/// Gets the escape character letting insert quotation characters inside a quoted field.
/// </summary>
/// <value>The escape character letting insert quotation characters inside a quoted field.</value>
public char Escape
{
get
{
return _escape;
}
}
/// <summary>
/// Gets the delimiter character separating each field.
/// </summary>
/// <value>The delimiter character separating each field.</value>
public char Delimiter
{
get
{
return _delimiter;
}
}
/// <summary>
/// Gets the quotation character wrapping every field.
/// </summary>
/// <value>The quotation character wrapping every field.</value>
public char Quote
{
get
{
return _quote;
}
}
/// <summary>
/// Indicates if field names are located on the first non commented line.
/// </summary>
/// <value><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</value>
public bool HasHeaders
{
get
{
return _hasHeaders;
}
}
/// <summary>
/// Indicates if spaces at the start and end of a field are trimmed.
/// </summary>
/// <value><see langword="true"/> if spaces at the start and end of a field are trimmed, otherwise, <see langword="false"/>.</value>
public bool TrimSpaces
{
get
{
return _trimSpaces;
}
}
/// <summary>
/// Gets the buffer size.
/// </summary>
public int BufferSize
{
get
{
return _bufferSize;
}
}
/// <summary>
/// Gets or sets the default action to take when a parsing error has occured.
/// </summary>
/// <value>The default action to take when a parsing error has occured.</value>
public ParseErrorAction DefaultParseErrorAction
{
get
{
return _defaultParseErrorAction;
}
set
{
_defaultParseErrorAction = value;
}
}
/// <summary>
/// Gets or sets the action to take when a field is missing.
/// </summary>
/// <value>The action to take when a field is missing.</value>
public MissingFieldAction MissingFieldAction
{
get
{
return _missingFieldAction;
}
set
{
_missingFieldAction = value;
}
}
/// <summary>
/// Gets or sets a value indicating if the reader supports multiline fields.
/// </summary>
/// <value>A value indicating if the reader supports multiline field.</value>
public bool SupportsMultiline
{
get
{
return _supportsMultiline;
}
set
{
_supportsMultiline = value;
}
}
/// <summary>
/// Gets or sets a value indicating if the reader will skip empty lines.
/// </summary>
/// <value>A value indicating if the reader will skip empty lines.</value>
public bool SkipEmptyLines
{
get
{
return _skipEmptyLines;
}
set
{
_skipEmptyLines = value;
}
}
#endregion
#region State
/// <summary>
/// Gets the maximum number of fields to retrieve for each record.
/// </summary>
/// <value>The maximum number of fields to retrieve for each record.</value>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
public int FieldCount
{
get
{
EnsureInitialize();
return _fieldCount;
}
}
/// <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 virtual bool EndOfStream
{
get
{
return _eof;
}
}
/// <summary>
/// Gets the field headers.
/// </summary>
/// <returns>The field headers or an empty array if headers are not supported.</returns>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
public string[] GetFieldHeaders()
{
EnsureInitialize();
Debug.Assert(_fieldHeaders != null, "Field headers must be non null.");
string[] fieldHeaders = new string[_fieldHeaders.Length];
for (int i = 0; i < fieldHeaders.Length; i++)
fieldHeaders[i] = _fieldHeaders[i];
return fieldHeaders;
}
/// <summary>
/// Gets the current record index in the CSV file.
/// </summary>
/// <value>The current record index in the CSV file.</value>
public virtual long CurrentRecordIndex
{
get
{
return _currentRecordIndex;
}
}
/// <summary>
/// Indicates if one or more field are missing for the current record.
/// Resets after each successful record read.
/// </summary>
public bool MissingFieldFlag
{
get { return _missingFieldFlag; }
}
/// <summary>
/// Indicates if a parse error occured for the current record.
/// Resets after each successful record read.
/// </summary>
public bool ParseErrorFlag
{
get { return _parseErrorFlag; }
}
#endregion
#endregion
#region Indexers
/// <summary>
/// Gets the field with the specified name and record position. <see cref="M:hasHeaders"/> must be <see langword="true"/>.
/// </summary>
/// <value>
/// The field with the specified name and record position.
/// </value>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="field"/> is <see langword="null"/> or an empty string.
/// </exception>
/// <exception cref="T:InvalidOperationException">
/// The CSV does not have headers (<see cref="M:HasHeaders"/> property is <see langword="false"/>).
/// </exception>
/// <exception cref="T:ArgumentException">
/// <paramref name="field"/> not found.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// Record index must be > 0.
/// </exception>
/// <exception cref="T:InvalidOperationException">
/// Cannot move to a previous record in forward-only mode.
/// </exception>
/// <exception cref="T:EndOfStreamException">
/// Cannot read record at <paramref name="record"/>.
/// </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 string this[int record, string field]
{
get
{
MoveTo(record);
return this[field];
}
}
/// <summary>
/// Gets the field at the specified index and record position.
/// </summary>
/// <value>
/// The field at the specified index and record position.
/// A <see langword="null"/> is returned if the field cannot be found for the record.
/// </value>
/// <exception cref="T:ArgumentOutOfRangeException">
/// <paramref name="field"/> must be included in [0, <see cref="M:FieldCount"/>[.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// Record index must be > 0.
/// </exception>
/// <exception cref="T:InvalidOperationException">
/// Cannot move to a previous record in forward-only mode.
/// </exception>
/// <exception cref="T:EndOfStreamException">
/// Cannot read record at <paramref name="record"/>.
/// </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 string this[int record, int field]
{
get
{
MoveTo(record);
return this[field];
}
}
/// <summary>
/// Gets the field with the specified name. <see cref="M:hasHeaders"/> must be <see langword="true"/>.
/// </summary>
/// <value>
/// The field with the specified name.
/// </value>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="field"/> is <see langword="null"/> or an empty string.
/// </exception>
/// <exception cref="T:InvalidOperationException">
/// The CSV does not have headers (<see cref="M:HasHeaders"/> property is <see langword="false"/>).
/// </exception>
/// <exception cref="T:ArgumentException">
/// <paramref name="field"/> not found.
/// </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 string this[string field]
{
get
{
if (string.IsNullOrEmpty(field))
throw new ArgumentNullException("field");
if (!_hasHeaders)
throw new InvalidOperationException(ExceptionMessage.NoHeaders);
int index = GetFieldIndex(field);
if (index < 0)
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ExceptionMessage.FieldHeaderNotFound, field), "field");
return this[index];
}
}
/// <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="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 virtual string this[int field]
{
get
{
return ReadField(field, false, false);
}
}
#endregion
#region Methods
#region EnsureInitialize
/// <summary>
/// Ensures that the reader is initialized.
/// </summary>
private void EnsureInitialize()
{
if (!_initialized)
this.ReadNextRecord(true, false);
Debug.Assert(_fieldHeaders != null);
Debug.Assert(_fieldHeaders.Length > 0 || (_fieldHeaders.Length == 0 && _fieldHeaderIndexes == null));
}
#endregion
#region GetFieldIndex
/// <summary>
/// Gets the field index for the provided header.
/// </summary>
/// <param name="header">The header to look for.</param>
/// <returns>The field index for the provided header. -1 if not found.</returns>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
public int GetFieldIndex(string header)
{
EnsureInitialize();
int index;
if (_fieldHeaderIndexes != null && _fieldHeaderIndexes.TryGetValue(header, out index))
return index;
else
return -1;
}
#endregion
#region CopyCurrentRecordTo
/// <summary>
/// Copies the field array of the current record to a one-dimensional array, starting at the beginning of the target array.
/// </summary>
/// <param name="array"> The one-dimensional <see cref="T:Array"/> that is the destination of the fields of the current record.</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="array"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// The number of fields in the record is greater than the available space from <paramref name="index"/> to the end of <paramref name="array"/>.
/// </exception>
public void CopyCurrentRecordTo(string[] array)
{
CopyCurrentRecordTo(array, 0);
}
/// <summary>
/// Copies the field array of the current record to a one-dimensional array, starting at the beginning of the target array.
/// </summary>
/// <param name="array"> The one-dimensional <see cref="T:Array"/> that is the destination of the fields of the current record.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="array"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="T:ArgumentOutOfRangeException">
/// <paramref name="index"/> is les than zero or is equal to or greater than the length <paramref name="array"/>.
/// </exception>
/// <exception cref="InvalidOperationException">
/// No current record.
/// </exception>
/// <exception cref="ArgumentException">
/// The number of fields in the record is greater than the available space from <paramref name="index"/> to the end of <paramref name="array"/>.
/// </exception>
public void CopyCurrentRecordTo(string[] array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
if (index < 0 || index >= array.Length)
throw new ArgumentOutOfRangeException("index", index, string.Empty);
if (_currentRecordIndex < 0 || !_initialized)
throw new InvalidOperationException(ExceptionMessage.NoCurrentRecord);
if (array.Length - index < _fieldCount)
throw new ArgumentException(ExceptionMessage.NotEnoughSpaceInArray, "array");
for (int i = 0; i < _fieldCount; i++)
{
if (_parseErrorFlag)
array[index + i] = null;
else
array[index + i] = this[i];
}
}
#endregion
#region GetCurrentRawData
/// <summary>
/// Gets the current raw CSV data.
/// </summary>
/// <remarks>Used for exception handling purpose.</remarks>
/// <returns>The current raw CSV data.</returns>
public string GetCurrentRawData()
{
if (_buffer != null && _bufferLength > 0)
return new string(_buffer, 0, _bufferLength);
else
return string.Empty;
}
#endregion
#region IsWhiteSpace
/// <summary>
/// Indicates whether the specified Unicode character is categorized as white space.
/// </summary>
/// <param name="c">A Unicode character.</param>
/// <returns><see langword="true"/> if <paramref name="c"/> is white space; otherwise, <see langword="false"/>.</returns>
private bool IsWhiteSpace(char c)
{
// Handle cases where the delimiter is a whitespace (e.g. tab)
if (c == _delimiter)
return false;
else
{
// See char.IsLatin1(char c) in Reflector
if (c <= '\x00ff')
return (c == ' ' || c == '\t');
else
return (System.Globalization.CharUnicodeInfo.GetUnicodeCategory(c) == System.Globalization.UnicodeCategory.SpaceSeparator);
}
}
#endregion
#region MoveTo
/// <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:InvalidOperationException">
/// Cannot move to a previous record in forward-only mode.
/// </exception>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
public virtual void MoveTo(long record)
{
if (record < 0)
throw new ArgumentOutOfRangeException("record", record, ExceptionMessage.RecordIndexLessThanZero);
if (record < _currentRecordIndex)
throw new InvalidOperationException(ExceptionMessage.CannotMovePreviousRecordInForwardOnly);
// Get number of record to read
long offset = record - _currentRecordIndex;
if (offset > 0)
{
do
{
if (!ReadNextRecord())
throw new EndOfStreamException(string.Format(CultureInfo.InvariantCulture, ExceptionMessage.CannotReadRecordAtIndex, _currentRecordIndex - offset));
}
while (--offset > 0);
}
}
#endregion
#region ParseNewLine
/// <summary>
/// Parses a new line delimiter.
/// </summary>
/// <param name="pos">The starting position of the parsing. Will contain the resulting end position.</param>
/// <returns><see langword="true"/> if a new line delimiter was found; otherwise, <see langword="false"/>.</returns>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
private bool ParseNewLine(ref int pos)
{
Debug.Assert(pos <= _bufferLength);
// Check if already at the end of the buffer
if (pos == _bufferLength)
{
pos = 0;
if (!ReadBuffer())
return false;
}
char c = _buffer[pos];
// Treat \r as new line only if it's not the delimiter
if (c == '\r' && _delimiter != '\r')
{
pos++;
// Skip following \n (if there is one)
if (pos < _bufferLength)
{
if (_buffer[pos] == '\n')
pos++;
}
else
{
if (ReadBuffer())
{
if (_buffer[0] == '\n')
pos = 1;
else
pos = 0;
}
}
if (pos >= _bufferLength)
{
ReadBuffer();
pos = 0;
}
return true;
}
else if (c == '\n')
{
pos++;
if (pos >= _bufferLength)
{
ReadBuffer();
pos = 0;
}
return true;
}
return false;
}
/// <summary>
/// Determines whether the character at the specified position is a new line delimiter.
/// </summary>
/// <param name="pos">The position of the character to verify.</param>
/// <returns>
/// <see langword="true"/> if the character at the specified position is a new line delimiter; otherwise, <see langword="false"/>.
/// </returns>
private bool IsNewLine(int pos)
{
Debug.Assert(pos < _bufferLength);
char c = _buffer[pos];
if (c == '\n')
return true;
else if (c == '\r' && _delimiter != '\r')
return true;
else
return false;
}
#endregion
#region ReadBuffer
/// <summary>
/// Fills the buffer with data from the reader.
/// </summary>
/// <returns><see langword="true"/> if data was successfully read; otherwise, <see langword="false"/>.</returns>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
private bool ReadBuffer()
{
if (_eof)
return false;
CheckDisposed();
_bufferLength = _reader.Read(_buffer, 0, _bufferSize);
if (_bufferLength > 0)
return true;
else
{
_eof = true;
_buffer = null;
return false;
}
}
#endregion
#region ReadField
/// <summary>
/// Reads the field at the specified index.
/// Any unread fields with an inferior index will also be read as part of the required parsing.
/// </summary>
/// <param name="field">The field index.</param>
/// <param name="initializing">Indicates if the reader is currently initializing.</param>
/// <param name="discardValue">Indicates if the value(s) are discarded.</param>
/// <returns>
/// The field at the specified index.
/// A <see langword="null"/> indicates that an error occured or that the last field has been reached during initialization.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="field"/> is out of range.
/// </exception>
/// <exception cref="InvalidOperationException">
/// There is no current record.
/// </exception>
/// <exception cref="MissingFieldCsvException">
/// The CSV data appears to be missing a field.
/// </exception>
/// <exception cref="MalformedCsvException">
/// The CSV data appears to be malformed.
/// </exception>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
private string ReadField(int field, bool initializing, bool discardValue)
{
if (!initializing)
{
if (field < 0 || field >= _fieldCount)
throw new ArgumentOutOfRangeException("field", field, string.Format(CultureInfo.InvariantCulture, ExceptionMessage.FieldIndexOutOfRange, field));
if (_currentRecordIndex < 0)
throw new InvalidOperationException(ExceptionMessage.NoCurrentRecord);
// Directly return field if cached
if (_fields[field] != null)
return _fields[field];
else if (_missingFieldFlag)
return HandleMissingField(null, field, ref _nextFieldStart);
}
CheckDisposed();
int index = _nextFieldIndex;
while (index < field + 1)
{
// Handle case where stated start of field is past buffer
// This can occur because _nextFieldStart is simply 1 + last char position of previous field
if (_nextFieldStart == _bufferLength)
{
_nextFieldStart = 0;
// Possible EOF will be handled later (see Handle_EOF1)
ReadBuffer();
}
string value = null;
if (_missingFieldFlag)
{
value = HandleMissingField(value, index, ref _nextFieldStart);
}
else if (_nextFieldStart == _bufferLength)
{
// Handle_EOF1: Handle EOF here
// If current field is the requested field, then the value of the field is "" as in "f1,f2,f3,(\s*)"
// otherwise, the CSV is malformed
if (index == field)
{
if (!discardValue)
{
value = string.Empty;
_fields[index] = value;
}
}
else
{
value = HandleMissingField(value, index, ref _nextFieldStart);
}
}
else
{
// Trim spaces at start
if (_trimSpaces)
SkipWhiteSpaces(ref _nextFieldStart);
if (_eof)
value = string.Empty;
else if (_buffer[_nextFieldStart] != _quote)
{
// Non-quoted field
int start = _nextFieldStart;
int pos = _nextFieldStart;
for (; ; )
{
while (pos < _bufferLength)
{
char c = _buffer[pos];
if (c == _delimiter)
{
_nextFieldStart = pos + 1;
break;
}
else if (c == '\r' || c == '\n')
{
_nextFieldStart = pos;
_eol = true;
break;
}
else
pos++;
}
if (pos < _bufferLength)
break;
else
{
if (!discardValue)
value += new string(_buffer, start, pos - start);
start = 0;
pos = 0;
_nextFieldStart = 0;
if (!ReadBuffer())
break;
}
}
if (!discardValue)
{
if (!_trimSpaces)
{
if (!_eof && pos > start)
value += new string(_buffer, start, pos - start);
}
else
{
if (!_eof && pos > start)
{
// Do the trimming
pos--;
while (pos > -1 && IsWhiteSpace(_buffer[pos]))
pos--;
pos++;
if (pos > 0)
value += new string(_buffer, start, pos - start);
}
else
pos = -1;
// If pos <= 0, that means the trimming went past buffer start,
// and the concatenated value needs to be trimmed too.
if (pos <= 0)
{
pos = (value == null ? -1 : value.Length - 1);
// Do the trimming
while (pos > -1 && IsWhiteSpace(value[pos]))
pos--;
pos++;
if (pos > 0 && pos != value.Length)
value = value.Substring(0, pos);
}
}
if (value == null)
value = string.Empty;
}
if (_eol || _eof)
{
_eol = ParseNewLine(ref _nextFieldStart);
// Reaching a new line is ok as long as the parser is initializing or it is the last field
if (!initializing && index != _fieldCount - 1)
{
if (value != null && value.Length == 0)
value = null;
value = HandleMissingField(value, index, ref _nextFieldStart);
}
}
if (!discardValue)
_fields[index] = value;
}
else
{
// Quoted field
// Skip quote
int start = _nextFieldStart + 1;
int pos = start;
bool quoted = true;
bool escaped = false;
for (; ; )
{
while (pos < _bufferLength)
{
char c = _buffer[pos];
if (escaped)
{
escaped = false;
start = pos;
}
// IF current char is escape AND (escape and quote are different OR next char is a quote)
else if (c == _escape && (_escape != _quote || (pos + 1 < _bufferLength && _buffer[pos + 1] == _quote) || (pos + 1 == _bufferLength && _reader.Peek() == _quote)))
{
if (!discardValue)
value += new string(_buffer, start, pos - start);
escaped = true;
}
else if (c == _quote)
{
quoted = false;
break;
}
pos++;
}
if (!quoted)
break;
else
{
if (!discardValue && !escaped)
value += new string(_buffer, start, pos - start);
start = 0;
pos = 0;
_nextFieldStart = 0;
if (!ReadBuffer())
{
HandleParseError(new MalformedCsvException(GetCurrentRawData(), _nextFieldStart, Math.Max(0, _currentRecordIndex), index), ref _nextFieldStart);
return null;
}
}
}
if (!_eof)
{
// Append remaining parsed buffer content
if (!discardValue && pos > start)
value += new string(_buffer, start, pos - start);
// Skip quote
_nextFieldStart = pos + 1;
// Skip whitespaces between the quote and the delimiter/eol
SkipWhiteSpaces(ref _nextFieldStart);
// Skip delimiter
bool delimiterSkipped;
if (_nextFieldStart < _bufferLength && _buffer[_nextFieldStart] == _delimiter)
{
_nextFieldStart++;
delimiterSkipped = true;
}
else
{
delimiterSkipped = false;
}
// Skip new line delimiter if initializing or last field
// (if the next field is missing, it will be caught when parsed)
if (!_eof && !delimiterSkipped && (initializing || index == _fieldCount - 1))
_eol = ParseNewLine(ref _nextFieldStart);
// If no delimiter is present after the quoted field and it is not the last field, then it is a parsing error
if (!delimiterSkipped && !_eof && !(_eol || IsNewLine(_nextFieldStart)))
HandleParseError(new MalformedCsvException(GetCurrentRawData(), _nextFieldStart, Math.Max(0, _currentRecordIndex), index), ref _nextFieldStart);
}
if (!discardValue)
{
if (value == null)
value = string.Empty;
_fields[index] = value;
}
}
}
_nextFieldIndex = Math.Max(index + 1, _nextFieldIndex);
if (index == field)
{
// If initializing, return null to signify the last field has been reached
if (initializing)
{
if (_eol || _eof)
return null;
else
return string.IsNullOrEmpty(value) ? string.Empty : value;
}
else
return value;
}
index++;
}
// Getting here is bad ...
HandleParseError(new MalformedCsvException(GetCurrentRawData(), _nextFieldStart, Math.Max(0, _currentRecordIndex), index), ref _nextFieldStart);
return null;
}
#endregion
#region ReadNextRecord
/// <summary>
/// Reads the next record.
/// </summary>
/// <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>
public bool ReadNextRecord()
{
return ReadNextRecord(false, false);
}
/// <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 virtual bool ReadNextRecord(bool onlyReadHeaders, bool skipToNextLine)
{
if (_eof)
{
if (_firstRecordInCache)
{
_firstRecordInCache = false;
_currentRecordIndex++;
return true;
}
else
return false;
}
CheckDisposed();
if (!_initialized)
{
_buffer = new char[_bufferSize];
// will be replaced if and when headers are read
_fieldHeaders = new string[0];
if (!ReadBuffer())
return false;
if (!SkipEmptyAndCommentedLines(ref _nextFieldStart))
return false;
// Keep growing _fields array until the last field has been found
// and then resize it to its final correct size
_fieldCount = 0;
_fields = new string[16];
while (ReadField(_fieldCount, true, false) != null)
{
if (_parseErrorFlag)
{
_fieldCount = 0;
Array.Clear(_fields, 0, _fields.Length);
_parseErrorFlag = false;
_nextFieldIndex = 0;
}
else
{
_fieldCount++;
if (_fieldCount == _fields.Length)
Array.Resize<string>(ref _fields, (_fieldCount + 1) * 2);
}
}
// _fieldCount contains the last field index, but it must contains the field count,
// so increment by 1
_fieldCount++;
if (_fields.Length != _fieldCount)
Array.Resize<string>(ref _fields, _fieldCount);
_initialized = true;
// If headers are present, call ReadNextRecord again
if (_hasHeaders)
{
// Don't count first record as it was the headers
_currentRecordIndex = -1;
_firstRecordInCache = false;
_fieldHeaders = new string[_fieldCount];
_fieldHeaderIndexes = new Dictionary<string, int>(_fieldCount, _fieldHeaderComparer);
for (int i = 0; i < _fields.Length; i++)
{
_fieldHeaders[i] = _fields[i];
_fieldHeaderIndexes.Add(_fields[i], i);
}
// Proceed to first record
if (!onlyReadHeaders)
{
// Calling again ReadNextRecord() seems to be simpler,
// but in fact would probably cause many subtle bugs because the derived does not expect a recursive behavior
// so simply do what is needed here and no more.
if (!SkipEmptyAndCommentedLines(ref _nextFieldStart))
return false;
Array.Clear(_fields, 0, _fields.Length);
_nextFieldIndex = 0;
_eol = false;
_currentRecordIndex++;
return true;
}
}
else
{
if (onlyReadHeaders)
{
_firstRecordInCache = true;
_currentRecordIndex = -1;
}
else
{
_firstRecordInCache = false;
_currentRecordIndex = 0;
}
}
}
else
{
if (skipToNextLine)
SkipToNextLine(ref _nextFieldStart);
else if (_currentRecordIndex > -1 && !_missingFieldFlag)
{
// If not already at end of record, move there
if (!_eol && !_eof)
{
if (!_supportsMultiline)
SkipToNextLine(ref _nextFieldStart);
else
{
// a dirty trick to handle the case where extra fields are present
while (ReadField(_nextFieldIndex, true, true) != null)
{
}
}
}
}
if (!_firstRecordInCache && !SkipEmptyAndCommentedLines(ref _nextFieldStart))
return false;
if (_hasHeaders || !_firstRecordInCache)
_eol = false;
// Check to see if the first record is in cache.
// This can happen when initializing a reader with no headers
// because one record must be read to get the field count automatically
if (_firstRecordInCache)
_firstRecordInCache = false;
else
{
Array.Clear(_fields, 0, _fields.Length);
_nextFieldIndex = 0;
}
_missingFieldFlag = false;
_parseErrorFlag = false;
_currentRecordIndex++;
}
return true;
}
#endregion
#region SkipEmptyAndCommentedLines
/// <summary>
/// Skips empty and commented lines.
/// If the end of the buffer is reached, its content be discarded and filled again from the reader.
/// </summary>
/// <param name="pos">
/// The position in the buffer where to start parsing.
/// Will contains the resulting position after the operation.
/// </param>
/// <returns><see langword="true"/> if the end of the reader has not been reached; otherwise, <see langword="false"/>.</returns>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
private bool SkipEmptyAndCommentedLines(ref int pos)
{
if (pos < _bufferLength)
DoSkipEmptyAndCommentedLines(ref pos);
while (pos >= _bufferLength && !_eof)
{
if (ReadBuffer())
{
pos = 0;
DoSkipEmptyAndCommentedLines(ref pos);
}
else
return false;
}
return !_eof;
}
/// <summary>
/// <para>Worker method.</para>
/// <para>Skips empty and commented lines.</para>
/// </summary>
/// <param name="pos">
/// The position in the buffer where to start parsing.
/// Will contains the resulting position after the operation.
/// </param>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
private void DoSkipEmptyAndCommentedLines(ref int pos)
{
while (pos < _bufferLength)
{
if (_buffer[pos] == _comment)
{
pos++;
SkipToNextLine(ref pos);
}
else if (_skipEmptyLines && ParseNewLine(ref pos))
continue;
else
break;
}
}
#endregion
#region SkipWhiteSpaces
/// <summary>
/// Skips whitespace characters.
/// </summary>
/// <param name="pos">The starting position of the parsing. Will contain the resulting end position.</param>
/// <returns><see langword="true"/> if the end of the reader has not been reached; otherwise, <see langword="false"/>.</returns>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
private bool SkipWhiteSpaces(ref int pos)
{
for (; ; )
{
while (pos < _bufferLength && IsWhiteSpace(_buffer[pos]))
pos++;
if (pos < _bufferLength)
break;
else
{
pos = 0;
if (!ReadBuffer())
return false;
}
}
return true;
}
#endregion
#region SkipToNextLine
/// <summary>
/// Skips ahead to the next NewLine character.
/// If the end of the buffer is reached, its content be discarded and filled again from the reader.
/// </summary>
/// <param name="pos">
/// The position in the buffer where to start parsing.
/// Will contains the resulting position after the operation.
/// </param>
/// <returns><see langword="true"/> if the end of the reader has not been reached; otherwise, <see langword="false"/>.</returns>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
private bool SkipToNextLine(ref int pos)
{
// ((pos = 0) == 0) is a little trick to reset position inline
while ((pos < _bufferLength || (ReadBuffer() && ((pos = 0) == 0))) && !ParseNewLine(ref pos))
pos++;
return !_eof;
}
#endregion
#region HandleParseError
/// <summary>
/// Handles a parsing error.
/// </summary>
/// <param name="error">The parsing error that occured.</param>
/// <param name="pos">The current position in the buffer.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="error"/> is <see langword="null"/>.
/// </exception>
private void HandleParseError(MalformedCsvException error, ref int pos)
{
if (error == null)
throw new ArgumentNullException("error");
_parseErrorFlag = true;
switch (_defaultParseErrorAction)
{
case ParseErrorAction.ThrowException:
throw error;
case ParseErrorAction.RaiseEvent:
ParseErrorEventArgs e = new ParseErrorEventArgs(error, ParseErrorAction.ThrowException);
OnParseError(e);
switch (e.Action)
{
case ParseErrorAction.ThrowException:
throw e.Error;
case ParseErrorAction.RaiseEvent:
throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ExceptionMessage.ParseErrorActionInvalidInsideParseErrorEvent, e.Action), e.Error);
case ParseErrorAction.AdvanceToNextLine:
// already at EOL when fields are missing, so don't skip to next line in that case
if (!_missingFieldFlag && pos >= 0)
SkipToNextLine(ref pos);
break;
default:
throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, ExceptionMessage.ParseErrorActionNotSupported, e.Action), e.Error);
}
break;
case ParseErrorAction.AdvanceToNextLine:
// already at EOL when fields are missing, so don't skip to next line in that case
if (!_missingFieldFlag && pos >= 0)
SkipToNextLine(ref pos);
break;
default:
throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, ExceptionMessage.ParseErrorActionNotSupported, _defaultParseErrorAction), error);
}
}
#endregion
#region HandleMissingField
/// <summary>
/// Handles a missing field error.
/// </summary>
/// <param name="value">The partially parsed value, if available.</param>
/// <param name="fieldIndex">The missing field index.</param>
/// <param name="currentPosition">The current position in the raw data.</param>
/// <returns>
/// The resulting value according to <see cref="M:MissingFieldAction"/>.
/// If the action is set to <see cref="T:MissingFieldAction.TreatAsParseError"/>,
/// then the parse error will be handled according to <see cref="DefaultParseErrorAction"/>.
/// </returns>
private string HandleMissingField(string value, int fieldIndex, ref int currentPosition)
{
if (fieldIndex < 0 || fieldIndex >= _fieldCount)
throw new ArgumentOutOfRangeException("fieldIndex", fieldIndex, string.Format(CultureInfo.InvariantCulture, ExceptionMessage.FieldIndexOutOfRange, fieldIndex));
_missingFieldFlag = true;
for (int i = fieldIndex + 1; i < _fieldCount; i++)
_fields[i] = null;
if (value != null)
return value;
else
{
switch (_missingFieldAction)
{
case MissingFieldAction.ParseError:
HandleParseError(new MissingFieldCsvException(GetCurrentRawData(), currentPosition, Math.Max(0, _currentRecordIndex), fieldIndex), ref currentPosition);
return value;
case MissingFieldAction.ReplaceByEmpty:
return string.Empty;
case MissingFieldAction.ReplaceByNull:
return null;
default:
throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, ExceptionMessage.MissingFieldActionNotSupported, _missingFieldAction));
}
}
}
#endregion
#endregion
#region IDataReader support methods
/// <summary>
/// Validates the state of the data reader.
/// </summary>
/// <param name="validations">The validations to accomplish.</param>
/// <exception cref="InvalidOperationException">
/// No current record.
/// </exception>
/// <exception cref="InvalidOperationException">
/// This operation is invalid when the reader is closed.
/// </exception>
private void ValidateDataReader(DataReaderValidations validations)
{
if ((validations & DataReaderValidations.IsInitialized) != 0 && !_initialized)
throw new InvalidOperationException(ExceptionMessage.NoCurrentRecord);
if ((validations & DataReaderValidations.IsNotClosed) != 0 && _isDisposed)
throw new InvalidOperationException(ExceptionMessage.ReaderClosed);
}
/// <summary>
/// Copy the value of the specified field to an array.
/// </summary>
/// <param name="field">The index of the field.</param>
/// <param name="fieldOffset">The offset in the field value.</param>
/// <param name="destinationArray">The destination array where the field value will be copied.</param>
/// <param name="destinationOffset">The destination array offset.</param>
/// <param name="length">The number of characters to copy from the field value.</param>
/// <returns></returns>
private long CopyFieldToArray(int field, long fieldOffset, Array destinationArray, int destinationOffset, int length)
{
EnsureInitialize();
if (field < 0 || field >= _fieldCount)
throw new ArgumentOutOfRangeException("field", field, string.Format(CultureInfo.InvariantCulture, ExceptionMessage.FieldIndexOutOfRange, field));
if (fieldOffset < 0 || fieldOffset >= int.MaxValue)
throw new ArgumentOutOfRangeException("fieldOffset");
// Array.Copy(...) will do the remaining argument checks
if (length == 0)
return 0;
string value = this[field];
if (value == null)
value = string.Empty;
Debug.Assert(fieldOffset < int.MaxValue);
Debug.Assert(destinationArray.GetType() == typeof(char[]) || destinationArray.GetType() == typeof(byte[]));
if (destinationArray.GetType() == typeof(char[]))
Array.Copy(value.ToCharArray((int) fieldOffset, length), 0, destinationArray, destinationOffset, length);
else
{
char[] chars = value.ToCharArray((int) fieldOffset, length);
byte[] source = new byte[chars.Length]; ;
for (int i = 0; i < chars.Length; i++)
source[i] = Convert.ToByte(chars[i]);
Array.Copy(source, 0, destinationArray, destinationOffset, length);
}
return length;
}
#endregion
#region IDataReader Members
int IDataReader.RecordsAffected
{
get
{
// For SELECT statements, -1 must be returned.
return -1;
}
}
bool IDataReader.IsClosed
{
get
{
return _eof;
}
}
bool IDataReader.NextResult()
{
ValidateDataReader(DataReaderValidations.IsNotClosed);
return false;
}
void IDataReader.Close()
{
Dispose();
}
bool IDataReader.Read()
{
ValidateDataReader(DataReaderValidations.IsNotClosed);
return ReadNextRecord();
}
int IDataReader.Depth
{
get
{
ValidateDataReader(DataReaderValidations.IsNotClosed);
return 0;
}
}
DataTable IDataReader.GetSchemaTable()
{
EnsureInitialize();
ValidateDataReader(DataReaderValidations.IsNotClosed);
DataTable schema = new DataTable("SchemaTable");
schema.Locale = CultureInfo.InvariantCulture;
schema.MinimumCapacity = _fieldCount;
schema.Columns.Add(SchemaTableColumn.AllowDBNull, typeof(bool)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.BaseColumnName, typeof(string)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.BaseSchemaName, typeof(string)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.BaseTableName, typeof(string)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.ColumnName, typeof(string)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.ColumnOrdinal, typeof(int)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.ColumnSize, typeof(int)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.DataType, typeof(object)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.IsAliased, typeof(bool)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.IsExpression, typeof(bool)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.IsKey, typeof(bool)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.IsLong, typeof(bool)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.IsUnique, typeof(bool)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.NumericPrecision, typeof(short)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.NumericScale, typeof(short)).ReadOnly = true;
schema.Columns.Add(SchemaTableColumn.ProviderType, typeof(int)).ReadOnly = true;
schema.Columns.Add(SchemaTableOptionalColumn.BaseCatalogName, typeof(string)).ReadOnly = true;
schema.Columns.Add(SchemaTableOptionalColumn.BaseServerName, typeof(string)).ReadOnly = true;
schema.Columns.Add(SchemaTableOptionalColumn.IsAutoIncrement, typeof(bool)).ReadOnly = true;
schema.Columns.Add(SchemaTableOptionalColumn.IsHidden, typeof(bool)).ReadOnly = true;
schema.Columns.Add(SchemaTableOptionalColumn.IsReadOnly, typeof(bool)).ReadOnly = true;
schema.Columns.Add(SchemaTableOptionalColumn.IsRowVersion, typeof(bool)).ReadOnly = true;
string[] columnNames;
if (_hasHeaders)
columnNames = _fieldHeaders;
else
{
columnNames = new string[_fieldCount];
for (int i = 0; i < _fieldCount; i++)
columnNames[i] = "Column" + i.ToString(CultureInfo.InvariantCulture);
}
// null marks columns that will change for each row
object[] schemaRow = new object[] {
true, // 00- AllowDBNull
null, // 01- BaseColumnName
string.Empty, // 02- BaseSchemaName
string.Empty, // 03- BaseTableName
null, // 04- ColumnName
null, // 05- ColumnOrdinal
int.MaxValue, // 06- ColumnSize
typeof(string), // 07- DataType
false, // 08- IsAliased
false, // 09- IsExpression
false, // 10- IsKey
false, // 11- IsLong
false, // 12- IsUnique
DBNull.Value, // 13- NumericPrecision
DBNull.Value, // 14- NumericScale
(int) DbType.String, // 15- ProviderType
string.Empty, // 16- BaseCatalogName
string.Empty, // 17- BaseServerName
false, // 18- IsAutoIncrement
false, // 19- IsHidden
true, // 20- IsReadOnly
false // 21- IsRowVersion
};
for (int i = 0; i < columnNames.Length; i++)
{
schemaRow[1] = columnNames[i]; // Base column name
schemaRow[4] = columnNames[i]; // Column name
schemaRow[5] = i; // Column ordinal
schema.Rows.Add(schemaRow);
}
return schema;
}
#endregion
#region IDataRecord Members
int IDataRecord.GetInt32(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
string value = this[i];
return Int32.Parse(value == null ? string.Empty : value, CultureInfo.CurrentCulture);
}
object IDataRecord.this[string name]
{
get
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return this[name];
}
}
object IDataRecord.this[int i]
{
get
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return this[i];
}
}
object IDataRecord.GetValue(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
if (((IDataRecord) this).IsDBNull(i))
return DBNull.Value;
else
return this[i];
}
bool IDataRecord.IsDBNull(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return (string.IsNullOrEmpty(this[i]));
}
long IDataRecord.GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return CopyFieldToArray(i, fieldOffset, buffer, bufferoffset, length);
}
byte IDataRecord.GetByte(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return Byte.Parse(this[i], CultureInfo.CurrentCulture);
}
Type IDataRecord.GetFieldType(int i)
{
EnsureInitialize();
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
if (i < 0 || i >= _fieldCount)
throw new ArgumentOutOfRangeException("i", i, string.Format(CultureInfo.InvariantCulture, ExceptionMessage.FieldIndexOutOfRange, i));
return typeof(string);
}
decimal IDataRecord.GetDecimal(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return Decimal.Parse(this[i], CultureInfo.CurrentCulture);
}
int IDataRecord.GetValues(object[] values)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
IDataRecord record = (IDataRecord) this;
for (int i = 0; i < _fieldCount; i++)
values[i] = record.GetValue(i);
return _fieldCount;
}
string IDataRecord.GetName(int i)
{
EnsureInitialize();
ValidateDataReader(DataReaderValidations.IsNotClosed);
if (i < 0 || i >= _fieldCount)
throw new ArgumentOutOfRangeException("i", i, string.Format(CultureInfo.InvariantCulture, ExceptionMessage.FieldIndexOutOfRange, i));
if (_hasHeaders)
return _fieldHeaders[i];
else
return "Column" + i.ToString(CultureInfo.InvariantCulture);
}
long IDataRecord.GetInt64(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return Int64.Parse(this[i], CultureInfo.CurrentCulture);
}
double IDataRecord.GetDouble(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return Double.Parse(this[i], CultureInfo.CurrentCulture);
}
bool IDataRecord.GetBoolean(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
string value = this[i];
int result;
if (Int32.TryParse(value, out result))
return (result != 0);
else
return Boolean.Parse(value);
}
Guid IDataRecord.GetGuid(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return new Guid(this[i]);
}
DateTime IDataRecord.GetDateTime(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return DateTime.Parse(this[i], CultureInfo.CurrentCulture);
}
int IDataRecord.GetOrdinal(string name)
{
EnsureInitialize();
ValidateDataReader(DataReaderValidations.IsNotClosed);
int index;
if (!_fieldHeaderIndexes.TryGetValue(name, out index))
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ExceptionMessage.FieldHeaderNotFound, name), "name");
return index;
}
string IDataRecord.GetDataTypeName(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return typeof(string).FullName;
}
float IDataRecord.GetFloat(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return Single.Parse(this[i], CultureInfo.CurrentCulture);
}
IDataReader IDataRecord.GetData(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
if (i == 0)
return this;
else
return null;
}
long IDataRecord.GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return CopyFieldToArray(i, fieldoffset, buffer, bufferoffset, length);
}
string IDataRecord.GetString(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return this[i];
}
char IDataRecord.GetChar(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return Char.Parse(this[i]);
}
short IDataRecord.GetInt16(int i)
{
ValidateDataReader(DataReaderValidations.IsInitialized | DataReaderValidations.IsNotClosed);
return Int16.Parse(this[i], CultureInfo.CurrentCulture);
}
#endregion
#region IEnumerable<string[]> Members
/// <summary>
/// Returns an <see cref="T:RecordEnumerator"/> that can iterate through CSV records.
/// </summary>
/// <returns>An <see cref="T:RecordEnumerator"/> that can iterate through CSV records.</returns>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
public CsvReader.RecordEnumerator GetEnumerator()
{
return new CsvReader.RecordEnumerator(this);
}
/// <summary>
/// Returns an <see cref="T:System.Collections.Generics.IEnumerator"/> that can iterate through CSV records.
/// </summary>
/// <returns>An <see cref="T:System.Collections.Generics.IEnumerator"/> that can iterate through CSV records.</returns>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
IEnumerator<string[]> IEnumerable<string[]>.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an <see cref="T:System.Collections.IEnumerator"/> that can iterate through CSV records.
/// </summary>
/// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can iterate through CSV records.</returns>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region IDisposable members
#if DEBUG
/// <summary>
/// Contains the stack when the object was allocated.
/// </summary>
private System.Diagnostics.StackTrace _allocStack;
#endif
/// <summary>
/// Contains the disposed status flag.
/// </summary>
private bool _isDisposed = false;
/// <summary>
/// Contains the locking object for multi-threading purpose.
/// </summary>
private readonly object _lock = new object();
/// <summary>
/// Occurs when the instance is disposed of.
/// </summary>
public event EventHandler Disposed;
/// <summary>
/// Gets a value indicating whether the instance has been disposed of.
/// </summary>
/// <value>
/// <see langword="true"/> if the instance has been disposed of; otherwise, <see langword="false"/>.
/// </value>
[System.ComponentModel.Browsable(false)]
public bool IsDisposed
{
get { return _isDisposed; }
}
/// <summary>
/// Raises the <see cref="M:Disposed"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.EventArgs"/> that contains the event data.</param>
protected virtual void OnDisposed(EventArgs e)
{
EventHandler handler = Disposed;
if (handler != null)
handler(this, e);
}
/// <summary>
/// Checks if the instance has been disposed of, and if it has, throws an <see cref="T:System.ComponentModel.ObjectDisposedException"/>; otherwise, does nothing.
/// </summary>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
/// <remarks>
/// Derived classes should call this method at the start of all methods and properties that should not be accessed after a call to <see cref="M:Dispose()"/>.
/// </remarks>
protected void CheckDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(this.GetType().FullName);
}
/// <summary>
/// Releases all resources used by the instance.
/// </summary>
/// <remarks>
/// Calls <see cref="M:Dispose(Boolean)"/> with the disposing parameter set to <see langword="true"/> to free unmanaged and managed resources.
/// </remarks>
public void Dispose()
{
if (!_isDisposed)
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
/// <summary>
/// Releases the unmanaged resources used by this instance and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">
/// <see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.
/// </param>
protected virtual void Dispose(bool disposing)
{
// Refer to http://www.bluebytesoftware.com/blog/PermaLink,guid,88e62cdf-5919-4ac7-bc33-20c06ae539ae.aspx
// Refer to http://www.gotdotnet.com/team/libraries/whitepapers/resourcemanagement/resourcemanagement.aspx
// No exception should ever be thrown except in critical scenarios.
// Unhandled exceptions during finalization will tear down the process.
if (!_isDisposed)
{
try
{
// Dispose-time code should call Dispose() on all owned objects that implement the IDisposable interface.
// "owned" means objects whose lifetime is solely controlled by the container.
// In cases where ownership is not as straightforward, techniques such as HandleCollector can be used.
// Large managed object fields should be nulled out.
// Dispose-time code should also set references of all owned objects to null, after disposing them. This will allow the referenced objects to be garbage collected even if not all references to the "parent" are released. It may be a significant memory consumption win if the referenced objects are large, such as big arrays, collections, etc.
if (disposing)
{
// Acquire a lock on the object while disposing.
if (_reader != null)
{
lock (_lock)
{
if (_reader != null)
{
_reader.Dispose();
_reader = null;
_buffer = null;
_eof = true;
}
}
}
}
}
finally
{
// Ensure that the flag is set
_isDisposed = true;
// Catch any issues about firing an event on an already disposed object.
try
{
OnDisposed(EventArgs.Empty);
}
catch { }
}
}
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the instance is reclaimed by garbage collection.
/// </summary>
~CsvReader()
{
#if DEBUG
Debug.WriteLine("FinalizableObject was not disposed" + _allocStack.ToString());
#endif
Dispose(false);
}
#endregion
}
}
|