Pergunta

Eu estou usando C #.

Eu estou tentando puxar um arquivo de texto para um objeto. Eu estou usando uma conexão ODBC e parece que este

Driver = {Microsoft Text Driver (* .txt; * .csv)}; DBQ = C: \ Users \ Proprietário \ Desktop \ IR \ IR_Files \ Absoluto; Extensions = asc, csv, aba, txt;

Eu sou capaz de fazer a conexão, mas eu não consigo me minhas colunas separadas. Eu estou usando um arquivo schema.ini, mas ele não está funcionando. Aqui está o meu arquivo de esquema.

[MyTextFile.CSV]
Format = Delimited (|)
ColNameHeader = false
Col1 = fullstockn Texto
col2 = FULLINFO Texto
MaxScanRows = 0
CharacterSet = ANSI

O arquivo de texto se parece com isso.

fullstockn | FULLINFO

"555555" |

Contenu: Neuf Ttudes sur l Alguns mais texto aqui .....

Foi útil?

Solução

Eu uso o seguinte seqüência de conexão

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

e um arquivo Schema.ini que começa tipicamente

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

e eu vou executar um leitor via

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

Além disso, o MSDN página no driver arquivo de texto foi útil quando eu investigados pela primeira vez este. Especificamente, o página no arquivo Schema.ini é bastante útil.

Outras dicas

Existe uma razão que você precisa para usar uma conexão ODBC para isso? Eu acho que seria mais fácil simplesmente abrir o arquivo de texto diretamente e analisá-lo sozinho.

Eu não sei se isso importa, mas ...

Você pode estar faltando o final "\" no seu atributo dbq ...

EDIT: Na verdade ... no texto que você postou, você tem 3 colunas, não 2 ... (2 tubos em vez de 1)

Eu sempre escrever o código-me para este tipo de op. Aqui está um exemplo de uma classe abstrata que escrevi para este fim não há muito tempo. Você pode modificá-lo ou subclasse-lo se você gosta

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;
    }
}

Tente usar essa seqüência de conexão

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

e

  • Tenha cuidado com o número de colunas
  • Coloque o schema.ini na mesma pasta do executável.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top