读取分隔的文本文件?

时间:2013-09-11 12:19:49

标签: c# .net io

我正在尝试从分隔的文本文件中读取,但所有内容都以一行和一列的形式返回。

我的连接字符串是

OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
    Path.GetDirectoryName(@textBox1txtPath.Text) + ";" + 
    "Extended Properties=\"text;HDR=YES;IMEX=1;Format=Delimited(|)\"");

我的文本文件是:

ItemNumber|ProductStatus|UPC
0000012|closed|2525

请协助

3 个答案:

答案 0 :(得分:4)

我不确切知道你需要什么,但你可以这样做:

如果您的string str包含全文,则可以

string[] lines = str.Split('\n');// split it to lines;

然后为你可以做的每一行

string[] cells = line.Split('|');// split a line to cells

如果我们将它提升到新的水平,我们可以做到:

public class line
{
  public int ItemNumber { get; set; }
  public string ProductStatus { get; set; }
  public int UPC { get; set; }

  public line(string currLine)
  {
     string[] cells = currLine.Split('|');
     int item;
     if(int.TryParse(cells[0], out item))
     {
        ItemNumber = item;
     }

     ProductStatus = cells[1];

     int upc;
     if (int.TryParse(cells[2], out upc))
     {
        UPC = upc;
     }
  }
}

然后:

string[] lines = str.Substring(str.IndexOf("\n")).Split('\n');// split it to lines;
List<line> tblLines = new List<line>();

foreach(string curr in lines)
{
    tblLines.Add(new line(curr);
}

答案 1 :(得分:4)

好的,所以一个选项将采取不同的方法。请考虑以下代码:

// read the entire file and store each line
// as a new element in a string[]
var lines = File.ReadAllLines(pathToFile);

// we can skip the first line because it's
// just headings - if you need the headings
// just grab them off the 0 index
for (int i = 1; i < lines.Length; i++)
{
    var vals = lines[i].Split('|');

    // do something with the vals because
    // they are now in a zero-based array
}

这消除了连接字符串的怪异性,消除了Odbc驱动程序的开销,并大大增加了代码的可读性。

答案 2 :(得分:3)

它在框架中是正确的 - TextFieldParser。不要担心命名空间,它原本是一个人们从VB6转换的垫片,但它非常有用。这是一个SSCCE,它演示了它用于许多不同的分隔符:

class Program
{
    static void Main(string[] args)
    {
        var comma = @"one,""two, yo"",three";
        var tab = "one\ttwo, yo\tthee";
        var random = @"onelol""two, yo""lolthree";

        var parser = CreateParser(comma, ",");
        Console.WriteLine("Parsing " + comma);
        Dump(parser);
        Console.WriteLine();
        parser = CreateParser(tab, "\t");
        Console.WriteLine("Parsing " + tab);
        Dump(parser);
        Console.WriteLine();
        parser = CreateParser(random, "lol");
        Console.WriteLine("Parsing " + random);
        Dump(parser);
        Console.WriteLine();
        Console.ReadLine();
    }

    private static TextFieldParser CreateParser(string value, params string[] delims)
    {
        var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(ToStream(value));
        parser.Delimiters = delims;
        return parser;
    }

    private static void Dump(TextFieldParser parser)
    {
        while (!parser.EndOfData)
            foreach (var field in parser.ReadFields())
                Console.WriteLine(field);
    }

    static Stream ToStream(string value)
    {
        return new MemoryStream(Encoding.Default.GetBytes(value));
    }
}