C # Reading a File of Fixed Length - Trimming Space in Values

When I read a file with a fixed length, the value always remains without a space.

Exmple: folder c: \ temp contains 2 files

fs.txt

ITMHMC12-163 -0000153430.30
ITMHMC12-164 -0000000745.18

Schema.ini

[fs.txt]
ColNameHeader=False
Format=FixedLength
DateTimeFormat=yyyymmdd
Col1=RecordTypeSCFBody Text Width 3
Col2=InvoiceNumber Text Width 10
Col3=Amount Text Width 14

C # code to read a file ...

string fileName = @"C:\temp\fs.txt";
string dir = Path.GetDirectoryName(fileName);

DataTable dataTable;

using (OleDbConnection conn =
    new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;" +
        "Data Source=" + dir + ";" +
        "Extended Properties=\"Text;\""))
{
conn.Open();

using (OleDbDataAdapter adapter = new OleDbDataAdapter("select * from " + fileName, conn))
{

    dataTable = new DataTable();
    adapter.Fill(dataTable);
}
conn.Close();
}

Console.Write(dataTable.Rows[0][1].ToString()); <-- this line **

-> this line gives me "HMC12-163", but I expect "HMC12-163". Pay attention to the space!

Appreciate your help.

Many thanks! -Deb

+5
source share
2 answers

Typically, there are no documented settings to control this behavior. You can use the explication panel for the correct number of spaces in your code or SQL if trailing spaces are important:

const int maxInvoiceLength = 10;
string fileName = @"C:\temp\fs.txt";
string dir = Path.GetDirectoryName(fileName);

DataTable dataTable;

using (OleDbConnection conn =
    new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;" +
        "Data Source=" + dir + ";" +
        "Extended Properties=\"Text;\""))
    {
        conn.Open();

        string query = String.Format("SELECT RecordTypeSCFBody, LEFT(InvoiceNumber + SPACE({0}), {0}), Amount FROM {1}", maxInvoiceLength, fileName);
        using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
        {
            dataTable = new DataTable();
            adapter.Fill(dataTable);
        }
    }

    Console.Write(dataTable.Rows[0][1].ToString());
+1
source

, :

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\txtFilesFolder\;Extended Properties="text;HDR=No;FMT=Fixed";

"HDR = Yes"; , , . "HDR = No;" .
, Schema.ini.

, :

using (OleDbConnection conn =
    new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;" +
        "Data Source=" + dir + ";" +
        "Extended Properties=\"Text;HDR=No;FMT=Fixed\""))
+1

All Articles