Reading text-based Files in ASP.

Source: Internet
Author: User

Friday, July, 1:43 PM

Every time I need to work with the contents of text-based files on an ASP. 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 t O 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 are 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 has to look up.

The Microsoft.VisualBasic Library is a collection of namespaces containing a miscellany of components and utilities. Most of the them seem to provide VB6 developers with something that they would be familiar with such as. NET implementations of The string-related Left Right and methods, but despite their name (and the fact that MSDN examples is all vb-only), the L Ibrary is pure. NET code and can being used with any. NET compliant language.  C # Projects do don't include a reference to Microsoft.VisualBasic by default, so need to use the Add References dialog to add it yourself:

A TextFieldParser instance can is initialised from a number of sources:a stream, a physical file on disk, or a TextReader . The first Options is likely to being used more often in ASP. This first example illustrates creating a from the TextFieldParser 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 ();}

TextFieldParserthe is instantiated within a using block because it implements IDisposable , and the using block ensures that the object wil L 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 a 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

The 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-Specify the field delimiters used in the file
TextFieldType(property) Specify whether the file is Delimited orFixedWidth TextFieldType.Delimited
HasFieldsEnclosedInQuotes(property) BooleanIndicating whether text fields is 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-on-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) Booleanindicating whether leading and trailing white space should is removed from fields true

Have instantiated and configured a TextFieldParser , you'll want to start accessing the data in the text file. The parser has a ReadFields method, a-gobbles up content a line at a time. It returns an array of strings. It also has a property EndOfData which indicates whether there is any further lines of data to be read. The following code shows "How to" use the "This" and "method in" combination to read all line of data in a simple example:

var data = @ "1,potato,vegetable2,strawberry,fruit3,carrot,vegetable4,milk,dairy,5,apple,fruit6,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 has a header. The following sample features the same data with a header row, and illustrates how to copy the whole thing into a datatabl E:

var data = @ "Id,food,foodtype1,potato,vegetable2,strawberry,fruit3,carrot,vegetable4,milk,dairy,5,apple,fruit6, 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 property to being CommentTokens able to read a standard IIS log file into a DataTable where comme NT lines is 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 are configured to ignore lines beginning with the specified comment token, a bit of additi Onal code is used to extract, the field headers for the DataTable column names.

Summary

Next time need to parse a text file in a. NET application, rather than reaching for string manipulation functions, you Could consider using the in the TextFieldParser Microsoft.VisualBasic library.

Original link: http://www.mikesdotnetting.com/article/279/reading-text-based-files-in-asp-net

Reading text-based Files in ASP.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.