using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text; namespace CsvFile
{
/// <summary>
/// Determines how empty lines are interpreted when reading CSV files.
/// These values do not affect empty lines that occur within quoted fields
/// or empty lines that appear at the end of the input file.
/// </summary>
public enum EmptyLineBehavior
{
/// <summary>
/// Empty lines are interpreted as a line with zero columns.
/// </summary>
NoColumns,
/// <summary>
/// Empty lines are interpreted as a line with a single empty column.
/// </summary>
EmptyColumn,
/// <summary>
/// Empty lines are skipped over as though they did not exist.
/// </summary>
Ignore,
/// <summary>
/// An empty line is interpreted as the end of the input file.
/// </summary>
EndOfFile,
} /// <summary>
/// Common base class for CSV reader and writer classes.
/// </summary>
public abstract class CsvFileCommon
{
/// <summary>
/// These are special characters in CSV files. If a column contains any
/// of these characters, the entire column is wrapped in double quotes.
/// </summary>
protected char[] SpecialChars = new char[] { ',', '"', '\r', '\n' }; // Indexes into SpecialChars for characters with specific meaning
private const int DelimiterIndex = ;
private const int QuoteIndex = ; /// <summary>
/// Gets/sets the character used for column delimiters.
/// </summary>
public char Delimiter
{
get { return SpecialChars[DelimiterIndex]; }
set { SpecialChars[DelimiterIndex] = value; }
} /// <summary>
/// Gets/sets the character used for column quotes.
/// </summary>
public char Quote
{
get { return SpecialChars[QuoteIndex]; }
set { SpecialChars[QuoteIndex] = value; }
}
} /// <summary>
/// Class for reading from comma-separated-value (CSV) files
/// </summary>
public class CsvFileReader : CsvFileCommon, IDisposable
{
// Private members
private StreamReader Reader;
private string CurrLine;
private int CurrPos;
private EmptyLineBehavior EmptyLineBehavior; /// <summary>
/// Initializes a new instance of the CsvFileReader class for the
/// specified stream.
/// </summary>
/// <param name="stream">The stream to read from</param>
/// <param name="emptyLineBehavior">Determines how empty lines are handled</param>
public CsvFileReader(Stream stream,
EmptyLineBehavior emptyLineBehavior = EmptyLineBehavior.NoColumns)
{
Reader = new StreamReader(stream);
EmptyLineBehavior = emptyLineBehavior;
} /// <summary>
/// Initializes a new instance of the CsvFileReader class for the
/// specified file path.
/// </summary>
/// <param name="path">The name of the CSV file to read from</param>
/// <param name="emptyLineBehavior">Determines how empty lines are handled</param>
public CsvFileReader(string path,
EmptyLineBehavior emptyLineBehavior = EmptyLineBehavior.NoColumns)
{
Reader = new StreamReader(path);
EmptyLineBehavior = emptyLineBehavior;
} /// <summary>
/// Reads a row of columns from the current CSV file. Returns false if no
/// more data could be read because the end of the file was reached.
/// </summary>
/// <param name="columns">Collection to hold the columns read</param>
public bool ReadRow(List<string> columns)
{
// Verify required argument
if (columns == null)
throw new ArgumentNullException("columns"); ReadNextLine:
// Read next line from the file
CurrLine = Reader.ReadLine();
CurrPos = ;
// Test for end of file
if (CurrLine == null)
return false;
// Test for empty line
if (CurrLine.Length == )
{
switch (EmptyLineBehavior)
{
case EmptyLineBehavior.NoColumns:
columns.Clear();
return true;
case EmptyLineBehavior.Ignore:
goto ReadNextLine;
case EmptyLineBehavior.EndOfFile:
return false;
}
} // Parse line
string column;
int numColumns = ;
while (true)
{
// Read next column
if (CurrPos < CurrLine.Length && CurrLine[CurrPos] == Quote)
column = ReadQuotedColumn();
else
column = ReadUnquotedColumn();
// Add column to list
if (numColumns < columns.Count)
columns[numColumns] = column;
else
columns.Add(column);
numColumns++;
// Break if we reached the end of the line
if (CurrLine == null || CurrPos == CurrLine.Length)
break;
// Otherwise skip delimiter
Debug.Assert(CurrLine[CurrPos] == Delimiter);
CurrPos++;
}
// Remove any unused columns from collection
if (numColumns < columns.Count)
columns.RemoveRange(numColumns, columns.Count - numColumns);
// Indicate success
return true;
} /// <summary>
/// Reads a quoted column by reading from the current line until a
/// closing quote is found or the end of the file is reached. On return,
/// the current position points to the delimiter or the end of the last
/// line in the file. Note: CurrLine may be set to null on return.
/// </summary>
private string ReadQuotedColumn()
{
// Skip opening quote character
Debug.Assert(CurrPos < CurrLine.Length && CurrLine[CurrPos] == Quote);
CurrPos++; // Parse column
StringBuilder builder = new StringBuilder();
while (true)
{
while (CurrPos == CurrLine.Length)
{
// End of line so attempt to read the next line
CurrLine = Reader.ReadLine();
CurrPos = ;
// Done if we reached the end of the file
if (CurrLine == null)
return builder.ToString();
// Otherwise, treat as a multi-line field
builder.Append(Environment.NewLine);
} // Test for quote character
if (CurrLine[CurrPos] == Quote)
{
// If two quotes, skip first and treat second as literal
int nextPos = (CurrPos + );
if (nextPos < CurrLine.Length && CurrLine[nextPos] == Quote)
CurrPos++;
else
break; // Single quote ends quoted sequence
}
// Add current character to the column
builder.Append(CurrLine[CurrPos++]);
} if (CurrPos < CurrLine.Length)
{
// Consume closing quote
Debug.Assert(CurrLine[CurrPos] == Quote);
CurrPos++;
// Append any additional characters appearing before next delimiter
builder.Append(ReadUnquotedColumn());
}
// Return column value
return builder.ToString();
} /// <summary>
/// Reads an unquoted column by reading from the current line until a
/// delimiter is found or the end of the line is reached. On return, the
/// current position points to the delimiter or the end of the current
/// line.
/// </summary>
private string ReadUnquotedColumn()
{
int startPos = CurrPos;
CurrPos = CurrLine.IndexOf(Delimiter, CurrPos);
if (CurrPos == -)
CurrPos = CurrLine.Length;
if (CurrPos > startPos)
return CurrLine.Substring(startPos, CurrPos - startPos);
return String.Empty;
} // Propagate Dispose to StreamReader
public void Dispose()
{
Reader.Dispose();
}
} /// <summary>
/// Class for writing to comma-separated-value (CSV) files.
/// </summary>
public class CsvFileWriter : CsvFileCommon, IDisposable
{
// Private members
private StreamWriter Writer;
private string OneQuote = null;
private string TwoQuotes = null;
private string QuotedFormat = null; /// <summary>
/// Initializes a new instance of the CsvFileWriter class for the
/// specified stream.
/// </summary>
/// <param name="stream">The stream to write to</param>
public CsvFileWriter(Stream stream)
{
Writer = new StreamWriter(stream);
} /// <summary>
/// Initializes a new instance of the CsvFileWriter class for the
/// specified file path.
/// </summary>
/// <param name="path">The name of the CSV file to write to</param>
public CsvFileWriter(string path)
{
Writer = new StreamWriter(path);
} /// <summary>
/// Writes a row of columns to the current CSV file.
/// </summary>
/// <param name="columns">The list of columns to write</param>
public void WriteRow(List<string> columns)
{
// Verify required argument
if (columns == null)
throw new ArgumentNullException("columns"); // Ensure we're using current quote character
if (OneQuote == null || OneQuote[] != Quote)
{
OneQuote = String.Format("{0}", Quote);
TwoQuotes = String.Format("{0}{0}", Quote);
QuotedFormat = String.Format("{0}{{0}}{0}", Quote);
} // Write each column
for (int i = ; i < columns.Count; i++)
{
// Add delimiter if this isn't the first column
if (i > )
Writer.Write(Delimiter);
// Write this column
if (columns[i].IndexOfAny(SpecialChars) == -)
Writer.Write(columns[i]);
else
Writer.Write(QuotedFormat, columns[i].Replace(OneQuote, TwoQuotes));
}
Writer.WriteLine();
} // Propagate Dispose to StreamWriter
public void Dispose()
{
Writer.Dispose();
}
}
}

C# - CSV(Comma-Separated Values)文件读取.的更多相关文章

  1. python开发_csv(Comma Separated Values)_逗号分隔值_常用导入导出格式_完整版_博主推荐

    ## 最近出了一趟差,是从20号去的,今天回来...# 就把最近学习的python内容给大家分享一下...#''' 在python中,CSV(Comma Separated Values),从字面上面 ...

  2. Python文件处理(txt、csv文件读取)

    打开文件 使用Python内置的方法 open()可以打开文件 file object = open(file_name [, access_mode][, buffering]) file_name ...

  3. CSV文件读取类

    最近项目中,经常需要读取Csv文件.基本步骤是: (1)按行读取 (2)然后将一行数据按逗号,分割为字符串数组 (3)将各列字符串转换成相应类型的数据 ,如int double类型 写了一个简单的Cs ...

  4. 本地文件读取(csv,txt)时字符编码问题解决

    今天进行csv文件读取时,老是入库为空,因为其中有中文字符,我要通过中文字符映射成相应的编号(上升:1011,下降:1012),于是怎么也取不到编号.刚开始以为程序映射出了问题,最后日志打出来后,发现 ...

  5. csv、json 文件读取

    1.CSV 文件存储 1.1 写入 简单示例 import csv with open('data.csv', 'a') as csvfile: writer = csv.writer(csvfile ...

  6. cocos2d-x CSV文件读取 (Excel生成csv文件)

    实现类 CCSVParse.h #ifndef __C_CSV_PARSE__ #define __C_CSV_PARSE__ #include "cocos2d.h" #incl ...

  7. 计算机程序的思维逻辑 (64) - 常见文件类型处理: 属性文件/CSV/EXCEL/HTML/压缩文件

    对于处理文件,我们介绍了流的方式,57节介绍了字节流,58节介绍了字符流,同时,也介绍了比较底层的操作文件的方式,60节介绍了随机读写文件,61节介绍了内存映射文件,我们也介绍了对象的序列化/反序列化 ...

  8. Java编程的逻辑 (64) - 常见文件类型处理: 属性文件/CSV/EXCEL/HTML/压缩文件

    ​本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http: ...

  9. Python编码/文件读取/多线程

    Python编码/文件读取/多线程 个人笔记~~记录才有成长   编码/文件读取/多线程 编码 常用的一般是gbk.utf-8,而在python中字符串一般是用Unicode来操作,这样才能按照单个字 ...

随机推荐

  1. DBA优化SQL采用的WITH AS 用法简介

    一.WITH AS简介 WITH AS的用法从oracle 9i新增的,官方文档也称之为:subquery factoring;在进行复杂的查询.统计等操作时使用with as 子句可以大大提高性能! ...

  2. IEnumerable中的 Any方法

    IEnumerable类中的 Any方法,表示集合中有任何一元素满足条件,返回就true , 该方法有两个重载 1. 不带任何参数,表示集合中有元素 2. 参入一个 Func<TSource, ...

  3. centos 下 apache 重启启动命令

    apache 启动 usr/local/apache243/bin/apachectl start apache 重启 usr/local/apache243/bin/apachectl restar ...

  4. shell如何生成rpm包仓库列表文件的对比结果

    基本步骤: 1.切换至仓库目录RPM_LIST_DIR1和RPM_LIST_DIR2 2.ls列出仓库的rpm包文件并分别重定向至输出文件rpm_list_file1和rpm_list_file2 3 ...

  5. 常用排序算法之——选择排序(C语言+VC6.0平台)

    选择排序是另一种经典排序算法,核心思想是:在一趟找最小(大)数的过程中,先假设待排数据中的第一个数据即为最小(大)数据,然后循环将其他数据与该数据比较,每次比较时若小于该数据则让新数据成为最小(大)数 ...

  6. NET MVC+EF6+Bootstrap

    开源:ASP.NET MVC+EF6+Bootstrap开发框架   前言 我在博客园潜水两三年了,在这里看过很多大神的文章,也学到了很多东西.可以说我是汲取着博客园的营养成长的. 想当年,我也是拿1 ...

  7. linux 命令行更新sdk

    ./android list sdk --proxy-host android-mirror.bugly.qq.com --proxy-port 8080 --no-ui -a -s ./androi ...

  8. hdu 2079 选课时间(题目已修改,注意读题)

    http://acm.hdu.edu.cn/showproblem.php?pid=2079 背包 #include <cstdio> #include <cstring> # ...

  9. LINK : fatal error LNK1000: Internal error during IncrBuildImage

    一.下微软的补丁:KB948127补丁来解决,http://code.msdn.microsoft.com/KB948127.貌似安装了也不起作用二.如果下载的补丁没安装成功或下载失败,可以用下面的方 ...

  10. USENIX 最佳论文奖:擦除 Windows Azure 存储编码

     我们发表了一篇介绍Windows Azure 存储如何用编码方式擦除数据的论文,此论文在 2012 年 6 月的 USENIX 技术年会上荣获最佳论文奖.这是 MicrosoftResearch ...