2017-08-08 36 views
0

我有一个应用程序读取和解析txt文件到数据表(以后上传)。其中一些文件被压缩(GZip)。我已经尽可能地将压缩文件识别并读取成单行的数据表(基本上是文件的复制品)。我现在需要做的是将这些数据(在“|”)解析到另一个数据表(如果可能的话,在同一个数据表中原位)。阅读GZip压缩文件到数据表,然后解析这个数据到另一个数据表

var ReadTable = new DataTable(); 
        ReadTable.Columns.Add("Col1"); 
        ReadTable.Columns.Add("Col2"); 
        ReadTable.Columns.Add("Col3"); 
        ReadTable.Columns.Add("Col4"); 
        ReadTable.Columns.Add("Col5"); 

        var ZipReadTable = new DataTable(); 
        ZipReadTable.Columns.Add("ZipCol1"); 

        if (isZip == false) 
        { 
         TextFieldParser parser = new TextFieldParser(FileLocationNameOriginal); 
         parser.TextFieldType = FieldType.Delimited; 
         parser.SetDelimiters("|"); 
         //Read and parse all data in the file into a datatable 
         while (!parser.EndOfData) 
         { 
          ReadTable.Rows.Add(parser.ReadFields()); 
         } 
         parser.Close(); 
        } 
        else 
        { 
         using (Stream fileStream = File.OpenRead(FileLocationNameOriginal), 
          zippedStream = new GZipStream(fileStream, CompressionMode.Decompress)) 
         { 
          using (StreamReader reader = new StreamReader(zippedStream)) 
          { 
           string line; 
           while ((line = reader.ReadLine()) != null) 
           { 
            ZipReadTable.Rows.Add(reader.ReadLine()); 
           } 
          } 
         } 
        } 

我试图再次转换数据表为一个字符串,但使用TextFieldParser不与它的工作(我认为这仅仅是用于读取文件吗?)。 StreamWriter是我应该使用的吗?在此先感谢StackOverFlow!

回答

0

我想出了一个相当简单的解决方案:

var ZipReadTable = new DataTable(); 
     ZipReadTable.Columns.Add("ZipCol1"); 

     using (Stream fileStream = File.OpenRead(FileName), 
      zippedStream = new GZipStream(fileStream, CompressionMode.Decompress)) 
     { 
      using (StreamReader reader = new StreamReader(zippedStream)) 
      { 
       while (!reader.EndOfStream) 
       { 
        ZipReadTable.Rows.Add(reader.ReadLine()); 
       } 
      } 
     } 

     string[] ParsedLine = null; 
     string NotParsedLine = null; 
     char Delimiter = '|'; 

     for (int k = 0; k < ZipReadTable.Rows.Count; k++) 
     { 
      NotParsedLine = ZipReadTable.Rows[k][0].ToString(); 
      ParsedLine = NotParsedLine.Split(Delimiter); 
      OutputTable.Rows.Add(ParsedLine); 
     } 
     return (OutputTable); 
相关问题