Question

J'utilise C #.

J'essaie d'extraire un fichier texte vers un objet. J'utilise une connexion ODBC et cela ressemble à ceci

Pilote = {Pilote Microsoft Texte (* .txt; * .csv)}; Dbq = C: \ Utilisateurs \ Propriétaire \ Bureau \ IR \ IR_Files \ Absolute; Extensions = asc, csv, tab, txt;

Je peux établir la connexion mais je ne peux pas séparer mes colonnes. J'utilise un fichier schema.ini mais cela ne fonctionne pas. Voici mon fichier de schéma.

[MyTextFile.CSV]
Format = Délimité (|)
ColNameHeader = False
Col1 = fullstockn Texte
col2 = FULLINFO Texte
MaxScanRows = 0
CharacterSet = ANSI

Le fichier texte ressemble à ceci.

fullstockn | FULLINFO

"555555" |

Contenu: Neuf Ttudes sur l Plus de texte ici .....

Était-ce utile?

La solution

J'utilise la chaîne de connexion suivante

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

et un fichier Schema.ini qui commence généralement

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

et je vais exécuter un lecteur via

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

De même, la page MSDN sur le pilote de fichier texte a été utile lors de ma première enquête. Plus précisément, la page du Schema.ini fichier est très utile.

Autres conseils

Y a-t-il une raison pour laquelle vous devez utiliser une connexion ODBC pour cela? Je pense qu'il serait plus facile d'ouvrir le fichier texte directement et de l'analyser vous-même.

Je ne sais pas si c'est important mais ...

Il se peut que la fin de la phrase " \ " soit manquante. dans votre attribut dbq ...

EDIT: En fait ... dans le texte que vous avez posté, vous avez 3 colonnes, pas 2 ... (2 tuyaux au lieu de 1)

J'écris toujours le code moi-même pour ce genre d'opération. Voici un exemple de classe abstraite que j'ai écrite à cette fin il n'y a pas si longtemps. Vous pouvez le modifier ou le sous-classer si vous aimez

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

Essayez d'utiliser cette chaîne de connexion

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

et:

  • Attention au nombre de colonnes
  • Placez le fichier schema.ini dans le même dossier que l'exécutable.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top