这是我的代码,首先我要跳过前4个字母并拆分其余部分并阅读它以根据txt文件更新我的数据库。
StreamReader sr = null;
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
sr = new StreamReader(fs);
string lines = sr.ReadLine();
while (!sr.EndOfStream)
{
string[] words = lines.Split(' ');
string ReservationNumber = words[0];
double deposit = Convert.ToDouble((words[1]));
if (GetCustomer(ReservationNumber).Customer_Res_Number == ReservationNumber)
{
UpdateDeposit(ReservationNumber, deposit);
}
lines = sr.ReadLine();
}
}
答案 0 :(得分:1)
为什么不使用File
类和 Linq 而不是Stream
和Reader
?如果是Linq,可以轻松跳过4
热门文件的行 - Skip(4)
:
跳过4
顶部行(文件的标题?):
// Data (lines) to process
var lines = File
.ReadLines(filename)
.Skip(4) // <- Skip first 4 lines (file's caption?)
.Select(line => line.Split(' '))
.Select(words => new {
ReservationNumber = words[0],
deposit = Convert.ToDouble(words[1]),
})
.Where(rec => GetCustomer(rec.ReservationNumber).Customer_Res_Number ==
rec.ReservationNumber);
// Data Processing
foreach (var item in lines)
UpdateDeposit(item.ReservationNumber, item.deposit);
如果你想从第1行(校验和或类似的?)中跳过第1个4
个字符:
var lines = File
.ReadLines(filename)
.Select((line, index) => index == 0
? line.Substring(4) // <- Skip 4 first characters from the 1st line
: line)
.Select(line => line.Split(' '))
...
最后,如果您想从每个行跳过4
个字符:
var lines = File
.ReadLines(filename)
.Select(line => line.Substring(4)) // <- Skip 4 fisrt characters from each line
.Select(line => line.Split(' '))
...
答案 1 :(得分:0)
也许......?
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
string newline = line.Substring(3);
...
}