如何在使用OleDB读取文本文件时正确处理CR [英] How do I correctly handle CR when reading text files with OleDB
问题描述
我有标签分隔的文本文件。我创建了一个Schema.ini,像这样:
I have text files that are Tab delimited. I created a Schema.ini like so:
[MY_FILE.TAB]
Format=TabDelimited
ColNameHeader=False
Col1=id Short
Col2=data Text
代码我用它来读取它(C#):
This is the code I use to read it (C#):
using (var connection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\FolderToData\;Extended Properties='text;FMT=delimited'"))
{
using (var command = new OleDbCommand("SELECT * FROM MY_FILE.TAB", connection))
{
var table = new DataTable();
using (var adapter = new OleDbDataAdapter(command)
{
adapter.Fill(table);
}
}
}
一切正常,除了一件事。文本文件中的数据包含Carriage Returns [CR]不幸的是,OleDB / MicrosoftJet(或任何解析这些文件)都会同时处理([CR],[CRLF])。
Everything works fine, except for one thing. The data in the text file contains Carriage Returns [CR]. Records itself are separated by Carriage Return Line Feeds [CR][LF]. Unfortunately, OleDB / MicrosoftJet (or whatever parses these files) treats both ([CR], [CRLF]) the same.
MY_FILE.TAB的示例(数字和文字之间应该有一个Tab):
Example of MY_FILE.TAB (there should be a Tab between numbers and text):
1 One[CR][LF]
2 Two[CR][LF]
3 Th[CR]
ree[CR][LF]
4 Four[CR][LF]
在DataTable中给我5(格式错误)的行,而不是4。
Gives me 5 (malformed) Rows in the DataTable instead of 4.
我需要的是:
1 "One"
2 "Two"
3 "Th\nree"
4 "Four2
但我得到:
1 "One"
2 "Two"
3 "Th"
null null
4 "Four"
"ree" can't be converted to Int32 so first colum in fourth row is null.
如何配置OleDB来处理[CR]不同于[CR] [LF]?或任何其他想法?
How can I configure OleDB to treat [CR] different than [CR][LF]? Or any other Ideas?
推荐答案
我不相信你可以重新配置OLEDB直接这样做。
I don't believe you can reconfigure OLEDB to do this directly.
另一种方法是使用TextReader和TextWriter将文件处理成临时文件,扫描并将CR替换为某些特殊的转义序列。然后使用OLEDB读取这个替换临时文件;最后,将特殊转义序列替换回CR。
An alternative approach would be to use a TextReader and TextWriter to process the file into a temporary file, scanning for and replacing CR alone into some special escape sequence. Then use OLEDB to read this replacement temporary file; finally, replace the special escape sequence back to a CR.
这篇关于如何在使用OleDB读取文本文件时正确处理CR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!