Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何逐字阅读文本文件中的行?_C# - Fatal编程技术网

C# 如何逐字阅读文本文件中的行?

C# 如何逐字阅读文本文件中的行?,c#,C#,我有一个ASCII文本文件。我想逐行读取该文件,将其除以位置,然后使用C#将每个值保存到数据库中。我如何才能做到这一点?使用: 我猜你需要这样的东西 using (StreamReader reader = new StreamReader("file.txt")) { string line; while ((line = reader.ReadLine()) != null) { for(int

我有一个ASCII文本文件。我想逐行读取该文件,将其除以位置,然后使用C#将每个值保存到数据库中。我如何才能做到这一点?

使用:


我猜你需要这样的东西

    using (StreamReader reader = new StreamReader("file.txt"))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
                for(int i = 0; i < line.Length;  i++){
                     //do something with  line[i]  
                }

        }
    }
使用(StreamReader=newstreamreader(“file.txt”))
{
弦线;
而((line=reader.ReadLine())!=null)
{
for(int i=0;i
System.IO.File.ReadAllLines(“文件”)是获取文件每一行的数组的最简单方法,但会将整个内容加载到内存中,因此对于大文件可能不太好

大概是

foreach (var line in File.ReadAllLines("file.txt")) {
    var phoneNumber = line.Substring(0, 10); //get first 10 chars
    var zipCode = line.Substring(10, 5); //get next 5 chars
    ... etc
    ... store to DB.
}
或者,在LINQ语法中,您可以

var data = from line in File.ReadAllLines(filename)
           select new {Phone=line.Substring(0,10), Zip=line.Substring(10,5), ...};
foreach(var record in data) { 
    .. store to DB 
}

“按位置划分”是什么意思?请给出一个文本文件的示例,并详细说明您想要做什么。文件中的值是否用字符分隔,是否要拆分每一行并取出这些值?哪一部分?打开文本文件并读取它?把它分成几块?将其持久化到数据库?这是一行“1888888000000011064000000086764001117757 cruhbr‰”-00000000 126000000000000000000041200000000000504000000000000000000000000000000000000000“我如何先读取10,然后再读取5?”将该行划分为如下几块:`string chunk;int pos=0;//在Alex或tysHTTP chunk=line.Substring(位置10)的循环内;pos+=10;//用chunk=line.Substring(位置5)做一些事情;pos+=5;//用chunk做点什么对不起大家,我知道怎么读。我发送了一行有10个数据,第一行是0-7,第二行是8-12,依此类推到最后。我问我是怎么剪的?
var data = from line in File.ReadAllLines(filename)
           select new {Phone=line.Substring(0,10), Zip=line.Substring(10,5), ...};
foreach(var record in data) { 
    .. store to DB 
}