当前位置:编程学习 > C#/ASP.NET >>

请问 如何读取.txt文件中的数据

请问 如何读取.txt文件中的数据 --------------------编程问答-------------------- 下面的示例从 FileStream 读取内容,并将其写入到另一个 FileStream。 


using System;
using System.IO;

class Test
{

public static void Main()
{
    // Specify a file to read from and to create.
    string pathSource = @"c:\tests\source.txt";
    string pathNew = @"c:\tests\newfile.txt";

    try
    {

        using (FileStream fsSource = new FileStream(pathSource,
            FileMode.Open, FileAccess.Read))
        {

            // Read the source file into a byte array.
            byte[] bytes = new byte[fsSource.Length];
            int numBytesToRead = (int)fsSource.Length;
            int numBytesRead = 0;
            while (numBytesToRead > 0)
            {
                // Read may return anything from 0 to numBytesToRead.
                int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);

                // Break when the end of the file is reached.
                if (n == 0)
                    break;

                numBytesRead += n;
                numBytesToRead -= n;
            }
             numBytesToRead = bytes.Length;

            // Write the byte array to the other FileStream.
            using (FileStream fsNew = new FileStream(pathNew,
                FileMode.Create, FileAccess.Write))
            {
                fsNew.Write(bytes, 0, numBytesToRead);
            }
        }
    }
    catch (FileNotFoundException ioEx)
    {
        Console.WriteLine(ioEx.Message);
    }
}
}

--------------------编程问答-------------------- 可以使用FileStream类,BAIDU一下很多的 --------------------编程问答-------------------- StreamReader读取
http://www.cnblogs.com/gisdream/archive/2011/02/23/1962026.html --------------------编程问答-------------------- 给你个我之前写的一个例子,http://download.csdn.net/detail/appleyk/3180552 --------------------编程问答--------------------
http://blog.csdn.net/iamsuxiaobo/article/details/3022183

推荐使用这种方法,考虑很全面 --------------------编程问答--------------------
引用 3 楼 chinajiyong 的回复:
StreamReader读取
http://www.cnblogs.com/gisdream/archive/2011/02/23/1962026.html


不错   --------------------编程问答-------------------- 二楼的就行!! --------------------编程问答--------------------
引用 3 楼 chinajiyong 的回复:
StreamReader读取
http://www.cnblogs.com/gisdream/archive/2011/02/23/1962026.html

数据流读取 --------------------编程问答-------------------- File.ReadAllText() --------------------编程问答--------------------
引用 3 楼 chinajiyong 的回复:
StreamReader读取
http://www.cnblogs.com/gisdream/archive/2011/02/23/1962026.html

嗯,找到对应的内容后,再处理,如果要再写入到文本里边,就用streamwriter
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,