Domanda

Sto usando C #.

Sto cercando di inserire un file di testo in un oggetto. Sto usando una connessione ODBC e sembra così

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

Sono in grado di stabilire la connessione ma non riesco a separare le mie colonne. Sto usando un file schema.ini ma non funziona. Ecco il mio file di schema.

[] MyTextFile.CSV
Format = delimitato (|)
ColNameHeader = False
Col1 = testo fullstockn
col2 = Testo FULLINFO
MaxScanRows = 0
CharacterSet = ANSI

Il file di testo è simile al seguente.

fullstockn | FULLINFO

" 555555 " |

Contenu: Neuf Ttudes sur l Qualche altro testo qui .....

È stato utile?

Soluzione

Uso la seguente stringa di connessione

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

e un file Schema.ini che in genere inizia

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

e eseguirò un lettore tramite

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

Inoltre, la pagina MSDN sul driver del file di testo è stata utile quando ho esaminato per la prima volta questo. In particolare, la pagina nella Schema.ini file è abbastanza utile.

Altri suggerimenti

C'è un motivo per cui è necessario utilizzare una connessione ODBC per questo? Penserei che sarebbe più semplice aprire direttamente il file di testo e analizzarlo da soli.

Non so se questo conta ma ...

Potresti perdere il finale " \ " nell'attributo dbq ...

MODIFICA: In realtà ... nel testo che hai pubblicato, hai 3 colonne, non 2 ... (2 pipe invece di 1)

Scrivo sempre io stesso il codice per questo tipo di operazione. Ecco un esempio di una classe astratta che ho scritto per questo scopo non molto tempo fa. Puoi modificarlo o sottoclassarlo se vuoi

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

Prova a utilizzare questa stringa di connessione

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

e:

  • Attenzione al numero di colonne
  • Posiziona schema.ini nella stessa cartella dell'eseguibile.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top