Read text block of a file

0

I have a problem, I want to read all the SELECT of a file. The SELECT must be all separated.

The SELECTs are all separated by a space.

All SELECT should be stored in a ARRAY or in a IEnumerable .

Something like that I want to do, but read all the SELECT:

public static string[] LeeArchivo()
        {
              return File.ReadAllLines(rutaArchivo)
                .TakeWhile(s => !string.IsNullOrWhiteSpace(s))
                .ToArray();
        }

Is there a way to fix it?

Greetings

    
asked by Nahuel Picca 05.07.2018 в 15:06
source

2 answers

1

A very simple way you have to do this is this:

List<string> listaSQL = new List<string>();
using (StreamReader rd = new StreamReader(rutaArchivo))
{
    string SQL = "";
    while (!rd.EndOfStream) //Mientras no llegue al final del documento seguimos en el bucle
    {
        string linea = rd.ReadLine(); //Leemos la linea actual
        if (string.IsNullOrEmpty(linea)) //Si la linea esta vacía entonces añadimos el contenido en la Lista porque ya pasa a la siguiente query
        {
            listaSQL.Add(SQL);
            SQL = "";
        }
        else //Sino seguimos construyendo la query
        {
            SQL += linea;
        }
    }
    //Al salir del bucle añadimos la ultima query
    listaSQL.Add(SQL);
}
string[] sArray = listaSQL.ToArray(); //Lo pasamos a Array

This way, you will build querys SQL line by line and every time it detects a target it adds the query that you were building to the list and starts to build a new one.

    
answered by 05.07.2018 / 17:11
source
0

If each selection is exactly written in a line of text:

 List<string> selects = new List<string>();
 string line = "";
 new System.IO.StreamReader(@"c:\RutaArchivo.txt");  
 while((line = file.ReadLine()) != null)  
 {  
      if(line.StartWith("SELECT"))
      {
           selects.Add(line);
      }
 }  

 file.Close();  
 string[] array = selects.ToArray();

with your code

             return File.ReadAllLines(rutaArchivo)
            .TakeWhile(s => s.StartWith("SELECT"))
            .ToArray();

Multi line

 List<string> selects = new List<string>();
 new System.IO.StreamReader(@"c:\RutaArchivo.txt");  
 string line = "";
 while((line = file.ReadLine()))  
 {  
      if(line.StartWith("SELECT"))
      {
           string select = "";
           while(line != "")
           {
               if(line = file.ReadLine()) 
               {
                    select +=line +"\n";

               }
           }
           selects.Add(select);
      }
 }  

 file.Close();  
 string[] array = selects.ToArray();

I do not know how to do that in lamda ...

    
answered by 05.07.2018 в 15:34