Pregunta

Estoy usando C #.

Estoy tratando de extraer un archivo de texto a un objeto. Estoy usando una conexión ODBC y se ve así

Driver = {Microsoft Text Driver (* .txt; * .csv)}; Dbq = C: \ Users \ Owner \ Desktop \ IR \ IR_Files \ Absolute; Extensiones = asc, csv, tab, txt;

Puedo hacer la conexión pero no puedo separar mis columnas. Estoy usando un archivo schema.ini pero no funciona. Aquí está mi archivo de esquema.

[MyTextFile.CSV]
Formato = Delimitado (|)
ColNameHeader = False
Col1 = fullstockn Texto
col2 = FULLINFO Texto
MaxScanRows = 0
CharacterSet = ANSI

El archivo de texto tiene este aspecto.

fullstockn | FULLINFO

" 555555 " |

Contenido: Neuf Ttudes sur l Algún texto más aquí .....

¿Fue útil?

Solución

Uso la siguiente cadena de conexión

string connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"text;HDR=YES;Format=Delimited(|)\";", Path.GetDirectoryName(path));

y un archivo Schema.ini que generalmente comienza

[myFile.txt]
Format=Delimited(|)
TextDelimiter="none"

y ejecutaré un lector a través de

command.CommandText = String.Format("SELECT * FROM [{0}]", Path.GetFileName(path));
OleDbDataReader reader = command.ExecuteReader();

Además, la página MSDN en el controlador del archivo de texto fue útil cuando investigé esto por primera vez. Específicamente, la página en el Schema.ini file es bastante útil.

Otros consejos

¿Hay alguna razón por la que necesite usar una conexión ODBC para esto? Creo que sería más fácil abrir el archivo de texto directamente y analizarlo usted mismo.

No sé si esto importa pero ...

Puede que te falte el final " \ " en su atributo dbq ...

EDITAR: en realidad ... en el texto que publicó, tiene 3 columnas, no 2 ... (2 canales en lugar de 1)

Siempre escribo el código yo mismo para este tipo de operación. Aquí hay un ejemplo de una clase abstracta que escribí para este propósito no hace mucho tiempo. Puede modificarlo o subclasificarlo si lo desea

public abstract class ReadTextFile : ILoadable
{
    public string Path { get; set; }
    public UploadFileType FileType { get; set; }
    protected internal List<List<string>> Table { get; set; }
    public Guid BatchID { get; set; }

    /// <summary>
    /// Method that loads the raw text into a collection of strings
    /// </summary>
    /// <returns></returns>
    public bool Load()
    {
        Table = new List<List<string>>();
        var splitter = Convert.ToChar("\t");
        try
        {
            using (TextReader tr = new StreamReader(Path))
            {
                // Discard the first line
                String line = tr.ReadLine();

                // Read and display lines from the file until the end of the file is reached.
                while ((line = tr.ReadLine()) != null)
                {
                    Table.Add(line.Split(splitter).ToList<string>());
                }
                tr.Close();
                tr.Dispose();
            }
            return true;

        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return false;
        }
    }
    public string Left(string param, int length)
    {
        //we start at 0 since we want to get the characters starting from the
        //left and with the specified lenght and assign it to a variable
        string result = param.Substring(0, length);
        //return the result of the operation
        return result;
    }
    public string Right(string param, int length)
    {
        //start at the index based on the lenght of the sting minus
        //the specified lenght and assign it a variable
        string result = param.Substring(param.Length - length, length);
        //return the result of the operation
        return result;
    }
}

Intente usar esta cadena de conexión

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Owner\Desktop\IR\IR_Files\Absolute\MyTextFile.CSV;Extended Properties='text'

y:

  • Cuidado con el número de columnas
  • Coloque el schema.ini en la misma carpeta del ejecutable.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top