如何从文本文件逐行读取字符串,把它写入到一个字符串变量中?

解决方案 »

  1.   

    FileStream myfs=new FileStream(@"f:\du.txt",FileMode.Open,FileAccess.Read);
    StreamReader myreader=new StreamReader(myfs,System.Text.Encoding.Default);
    string s=String.Empty;
    string box;
    while((s=myreader.ReadLine())!=null)
    {
    box=s;
    }
      

  2.   

    string f=@"c:\test.txt";
    String line;
    StreamReader sr = new StreamReader(f);
    while ((line = sr.ReadLine()) != null) 
    {
    Console.WriteLine(line);
    }
      

  3.   

    刚才的对英文可能有问题,这样:StreamReader sr = new StreamReader(f,System.Text.Encoding.Default) ;
      

  4.   

    mystring=streamreader.readtoend()呵呵
      

  5.   

    最简单的方法是:string fileContent = File.ReadAll(fileName);
      

  6.   

    抱歉,File.ReadAll是.Net2.0的函数,1.1上还不能用,用下面这个例子:下面的代码示例读取整个文件,并在检测到文件尾时发出通知。[Visual Basic]
    Option Explicit On 
    Option Strict On
    Imports System
    Imports System.IO
    Public Class TextFromFile
        Private Const FILE_NAME As String = "MyFile.txt"
        Public Shared Sub Main()
            If Not File.Exists(FILE_NAME) Then
                Console.WriteLine("{0} does not exist.", FILE_NAME)
                Return
            End If
            Dim sr As StreamReader = File.OpenText(FILE_NAME)
            Dim input As String
            input = sr.ReadLine()
            While Not input Is Nothing
                Console.WriteLine(input)
                input = sr.ReadLine()
            End While
            Console.WriteLine("The end of the stream has been reached.")
            sr.Close()
        End Sub
    End Class[C#]
    using System;
    using System.IO;
    public class TextFromFile 
    {
        private const string FILE_NAME = "MyFile.txt";
        public static void Main(String[] args) 
        {
            if (!File.Exists(FILE_NAME)) 
            {
                Console.WriteLine("{0} does not exist.", FILE_NAME);
                return;
            }
            StreamReader sr = File.OpenText(FILE_NAME);
            String input;
            while ((input=sr.ReadLine())!=null) 
            {
                Console.WriteLine(input);
            }
            Console.WriteLine ("The end of the stream has been reached.");
            sr.Close();
        }