如何用VB.NET或C#读取文本文件
我想用vb.net或C#实现以下功能,希望大虾给予指导!
1.打开多个文件,程序自动从文件中截取固定长度的字符
2.从文件中截取固定长度的字符合并到一个文件中
我的文件名是PROG2.014,PROG2.015,PROG2.016,PROG2.017样式的,可以用excle,word,记事本等打开,其内容格式如下:
595458028 584688 00000
59545802802630900000
59545802877041800000
59545802857500600000
59545802883717200000
59545802858012800000
59545802881383400000
59545802882353100000
59545802882935700000
59545802875479000000
59545802834600500000
59545802854947800000
59545802855942500000
59545802855835300000
59545802855025600000
59545802855836100000
59545802857930700000
59545802899383500000
我要截取每一个文件中每一行从左往右第10起的6个字符,例如第一行的584688,第二行的026309等
补充:3.把合并到一起的数据插入到数据库art中的表tmp_art_list中
说明:每行的20个字符中前9个不一定是相同的,倒数5个字符也不一定相同,我要想法子取出从第10到15位的字符
答案:using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
string txt = "";
StreamReader sr = new StreamReader(@"D:\test.txt");
while (!sr.EndOfStream)
{
string str = sr.ReadLine();
str = str.Substring(9, 6);
txt += str + "\n";
}
sr.Close();
Console.Write(txt);
///以下为插入数据库代码...仅供参考
//string sql = string.Format("Insert into tmp_art_list(字段) values('{0}')",txt);
//SqlCommand command = new SqlCommand(sql,new SqlConnection("数据库连接字符串"));
//int EffectRowCount = command.ExecuteNonQuery();
//if (EffectRowCount > 0)
//{
// Console.WriteLine("执行成功!");
//}
//else
//{
// Console.WriteLine("执行失败!");
//}
Console.ReadLine();
}
}
}
其他:用substring(10,6) 首先使用Directory配合File类找出你需要的文件
foreach DirectoryInfo下面的文件,比较文件名是否是需要的,可以使用正则表达式
找到文件集之后分别打开,使用流读取
当然你可以ReadLine()进来之后用substring,或者使用Read()方法跳过9个字之后,开始读取6个字符,然后跳过所有字符直到行末
上一个:Vb.net中如何判断字段为空!!!
下一个:XP下用VB.NET编程,如何使用VB6.0风格控件