Reading Text-based Files In ASP.NET
Friday, July 17, 2015 1:43 PM
Every time I need to work with the contents of text-based files in an ASP.NET application I invariably start off thinking about using the various static methods on the System.IO.File
class to extract the text and then some string manipulation or Regex to parse the content into some kind of structure. And, just in time, I remember the TextFieldParser
class that hides itself away in the Microsoft.VisualBasic
assembly. The purpose of this article is to introduce this component to a wider audience, but also to serve me as an aide-mémoire in terms of the basic usage, which I always have to look up.
The Microsoft.VisualBasic library is a collection of namespaces containing a miscellany of components and utilities. Most of them seem to provide VB6 developers with something that they will be familiar with such as .NET implementations of the string-related Left
and Right
methods, but despite its name (and the fact that MSDN examples are all VB-only), the library is pure .NET code and can be used with any .NET compliant language. C# projects do not include a reference to Microsoft.VisualBasic by default, so you need to use the Add References dialog to add it yourself:
A TextFieldParser
instance can be initialised from a number of sources: a stream, a physical file on disk, or aTextReader
. The first two options are likely to be used more often in ASP.NET applications. This first example illustrates creating a TextFieldParser
from an uploaded file in an MVC application:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null)
{
if (file.ContentLength > 0)
{
using (var parser = new TextFieldParser(file.InputStream))
{
// ...
}
}
}
return View();
}
The TextFieldParser
is instantiated within a using
block because it implements IDisposable
, and the using
block ensures that the object will be displosed of safely and correctly. The next example sees a file path passed to the TextFieldParser
constructor:
var file = @"C:\test.csv";
using (var parser = new TextFieldParser(file))
{
//..
}
Finally, here's an example of the constructor that accepts a concrete implementation of the TextReader
:
var csv = @"1,Mike,Brind,www.mikesdotnetting.com";
using (var parser = new TextFieldParser(new StringReader(csv)))
{
// ...
}
Configuration
Configuration options are set through properties and methods. The key options are featured below:
Option | Description | Default |
---|---|---|
Delimiters (property) |
Specifies the field delimiters used in the text file. | null |
SetDelimiters (method) |
Alterntative way to specify the field delimiters used in the file | |
TextFieldType (property) |
Specify whether the file is Delimited orFixedWidth |
TextFieldType.Delimited |
HasFieldsEnclosedInQuotes (property) |
Boolean indicating whether text fields are enclosed in quotes |
true |
FieldWidths (property) |
An array of ints specifying the widths of individual fields in a fixed width file |
null |
SetFieldWidths (method) |
An alternative way to specify the widths of individual fields in a fixed width file | |
CommentTokens (property) |
An array specifying the tokens used to indicate comments in the file | null |
TrimWhiteSpace (property) |
Boolean indicating whether leading and trailing white space should be removed from fields |
true |
Having instantiated and configured a TextFieldParser
, you will want to start accessing the data in the text file. The parser has a ReadFields
method that gobbles up content a line at a time. It returns an array of strings. It also has an EndOfData
property which indicates whether there are any more lines of data to be read. The following code shows how to use this property and method in combination to read each line of data in a simple example:
var data = @"1,Potato,Vegetable
2,Strawberry,Fruit
3,Carrot,Vegetable
4,Milk,Dairy,
5,Apple,Fruit
6,Bread,Cereal"; using (var parser = new TextFieldParser(new StringReader(data)))
{
parser.Delimiters = new[] { "," };
while (!parser.EndOfData)
{
var row = parser.ReadFields();
var foodType = row[2];
}
}
The sample above doesn't have a header. The following sample features the same data with a header row, and illustrates how to copy the whole thing into a DataTable:
var data = @"Id,Food,FoodType
1,Potato,Vegetable
2,Strawberry,Fruit
3,Carrot,Vegetable
4,Milk,Dairy,
5,Apple,Fruit
6,Bread,Cereal"; using (var parser = new TextFieldParser(new StringReader(data)))
{
var headerRow = true;
var dt = new DataTable(); parser.Delimiters = new[] { "," }; while (!parser.EndOfData)
{
var currentRow = parser.ReadFields();
if (headerRow)
{
foreach (var field in currentRow)
{
dt.Columns.Add(field, typeof(object));
}
headerRow = false;
}
else
{
dt.Rows.Add(currentRow);
}
}
}
The final example shows how to apply the CommentTokens
property to be able to read a standard IIS log file into aDataTable
where comment lines are prefixed with a hash (#
) symbol:
var file = @"C:\Logs\W3SVC6\ex140210.log";
var commentTokens = new[] { "#" };
var headerRow = File.ReadAllLines(file).First(l => l.StartsWith("#Fields:"));
using (var parser = new TextFieldParser(file))
{
var dt = new DataTable();
var columns = headerRow.Replace("#Fields: ", string.Empty).Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var column in columns)
{
dt.Columns.Add(column, typeof(object));
}
parser.SetDelimiters(" ");
parser.CommentTokens = commentTokens;
while (!parser.EndOfData)
{
{
dt.Rows.Add(parser.ReadFields());
}
}
}
In this case, because the parser is configured to ignore lines beginning with the specified comment token, a bit of additional code is used to extract the field headers for the DataTable
column names.
Summary
Next time you need to parse a text file in a .NET application, rather than reaching for string manipulation functions, you could consider using the TextFieldParser
in the Microsoft.VisualBasic library.
原文链接:http://www.mikesdotnetting.com/article/279/reading-text-based-files-in-asp-net
Reading Text-based Files In ASP.NET的更多相关文章
- AsciiDoc Text based document generation
AsciiDoc Text based document generation AsciiDoc Home Page http://asciidoc.org/ AsciiDoc is a t ...
- How to easily concatenate text based on criteria in Excel? 如何将Excel中的文本按条件合并
To combine text with the unique ID numbers, you can extract the unique values first and then create ...
- Adding Cache-Control headers to Static Files in ASP.NET Core
Thanks to the ASP.NET Core middleware pipeline, it is relatively simple to add additional HTTP heade ...
- Reading Text from Images Using C#
Introduction By using Optical Character Recognition (OCR), you can detect and extract handwritten an ...
- Upload Files In ASP.NET Core 1.0 (Form POST And JQuery Ajax)
Uploading files is a common requirement in web applications. In ASP.NET Core 1.0 uploading files and ...
- PostgreSQL Reading Ad Writing Files、Execution System Instructions Vul
catalog . postgresql简介 . 文件读取/写入 . 命令执行 . 影响范围 . 恶意代码分析 . 缓解方案 1. postgresql简介 PostgreSQL 是一个自由的对象-关 ...
- HTTP based RESTful APIs - asp.net web api
1.HTTP http://www.w3.org/Protocols/rfc2616/rfc2616.html 2.REST是什么http://www.ics.uci.edu/~fielding/pu ...
- Uploading files using ASP.NET Web Api
http://chris.59north.com/post/Uploading-files-using-ASPNET-Web-Api
- Suspended Animation——《The Economist》阅读积累(考研英语二·2010 Reading Text 1)
[知识小百科] Damien Hirst(达米恩●赫斯特):生于1965年,是新一代英国艺术家的主要代表人物之一.他主导了90年代英国艺术发展并享有很高的国际声誉.赫斯特在1986年9月就读于伦敦大学 ...
随机推荐
- IT售前经验谈
在IT界,成功的完成一个项目需要销售人员.售前人员.项目实施人员(开发人员).售后服务人员等密切协作.本文从售前技术支持人员的角度,对售前技术支持工作的过程进行了描述,根据作者在售前的经验,提出了各环 ...
- Android Studio----- 无法打印---log----问题总结----华为坑深(转)
问题描述:安卓真机调试时 System.out.println 无法输出, err则可以:Log.e,w可以,但其他不行. 解决方法,按如下方式查看酷派手机默认设置日志未warn方式. 酷派手机: * ...
- Linux 简单按键中断处理流程
中断处理程序中不能延时.休眠之类的,一定要最快速.高效的执行完. // 功能:申请中断 // 参数1:中断号码,通过宏 IRA_EINT(x) 获取 // 参数2:中断的处理函数,填函数名 // 参数 ...
- PAT1018——最短路加DFS
http://pat.zju.edu.cn/contests/pat-a-practise/1018 在杭州各个点,有很多自助自行车的点,最大容纳点为CMAX,但比较适合的情况是CMAX/2, 现在从 ...
- 【转】使用JMeter进行负载测试——终极指南
使用JMeter进行负载测试——终极指南 这篇教程讨论的是JMeter,它是一款基于Java的.集合了几个应用程序.具有特定用途的负载和性能测试工具. 本篇主要涉及的内容: 解释一下JMeter的用途 ...
- nginx 的第三方模块ngx_http_accesskey_module 来实现下载文件的防盗链步骤(linux系统下)
nginx 的第三方模块ngx_http_accesskey_module 来实现下载文件的防盗链步骤(linux系统下),安装Nginx和HttpAccessKeyModule模块(参考LNMP环境 ...
- linnx常用命令学习
ll命令就相当于ls -l. [-][rwx][r-x][r--] [-] 代表这个文件名为目录或文件(d为目录-为文件) [rwx]为:拥有人的权限(rwx为可读.可写.可执行) [r-x]为:同群 ...
- js发送windows提示信息
js发送windows提示信息 效果图 代码 Notification.requestPermission(function() { if(Notification.permission === 'g ...
- storm和kafka整合
storm和kafka整合 依赖 <dependency> <groupId>org.apache.storm</groupId> <artifactId&g ...
- Aggregate可以做字符串累加、数值累加、最大最小值
Aggregate("", (m, n) => m + n + ".").TrimEnd('.'); .Aggregate(0, (m, n) => ...