怎么读取文本文件

主  题:  怎么读取文本文件?
作  者:  wushengshan (wushengshan)
等  级:  ^
信 誉 值:  100
所属论坛:  .NET技术 C#
问题点数:  20
回复次数:  11
发表时间:  2003-8-29 13:39:16

怎么读取一个指定路径下的一个文本文件里的内容赋给一个字符串变量(string aa)呢?



回复人: cocosoft(pengyun) ( 两星(中级)) 信誉:111 2003-8-29 13:43:09 得分:0

通过流来实现。

回复人: cnhgj(戏子) ( 五级(中级)) 信誉:100 2003-8-29 13:45:01 得分:0

读出内容后赋值给aa不就行了?

回复人: benzite(小禾) ( 二级(初级)) 信誉:100 2003-8-29 13:46:44 得分:1

using System.IO;
StreamReader sr=new StreamReader("path+fileName");
aa=sr.ReadToEnd();
sr.Close();

回复人: albert2000(albert) ( 二级(初级)) 信誉:100 2003-8-29 13:47:06 得分:1

using System;
using System.IO;
using System.Text;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";

        // Delete the file if it exists.
        if (!File.Exists(path)) 
        {
            // Create the file.
            using (FileStream fs = File.Create(path)) 
            {
                Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");

                // Add some information to the file.
                fs.Write(info, 0, info.Length);
            }
        }

        // Open the stream and read it back.
        using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None)) 
        {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);

            while (fs.Read(b,0,b.Length) > 0) 
            {
                Console.WriteLine(temp.GetString(b));
            }

            try 
            {
                // Try to get another handle to the same file.
                using (FileStream fs2 = File.Open(path, FileMode.Open)) 
                {
                    // Do some task here.
                }
            } 
            catch (Exception e) 
            {
                Console.Write("Opening the file twice is disallowed.");
                Console.WriteLine(", as expected: {0}", e.ToString());
            }
        }
    }
}

回复人: superzuoluo(球星) ( 三级(初级)) 信誉:100 2003-8-29 13:48:07 得分:1

StreamReader sReader = null;

try
{
    sReader = new StreamReader("c:\\1.txt", System.Text.Encoding.Default);

    string strText = null;
    while (sReader.Peek() != -1)
        strText += sReader.ReadLine() + "\r";

    MessageBox.Show(strText);
}
finally
{
    if (sReader != null)
        sReader.Close();
}

回复人: gujianxin(木头象) ( 五级(中级)) 信誉:100 2003-8-29 13:57:56 得分:1

1,full context read

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            using (StreamReader sr = new StreamReader("TestFile.txt", System.Text.Encoding.Default))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}

还要注意的就是字符集的问题,如果你的txt是ascii编码的话,就要注意了,一定要指明字符集

StreamReader sr = new StreamReader(@"c:\test1.txt",System.Text.Encoding.GetEncoding("GB2312"));

回复人: gujianxin(木头象) ( 五级(中级)) 信誉:100 2003-8-29 13:58:27 得分:1

2,如果你指的是读取有格式的ini文件,可以使用GetPrivateProfile* 系列API

/// <summary>
/// 从配置文件中取得数据库连接字符串 
/// 默认:Web方式,从Web.config 中取 GetConnStrWeb()
/// 桌面方式:从Windows目录下的eii.ini 中取 GetConnStrDeskTop()
/// </summary>
public class SQLConnString
{
    private const string USER = "User id";
    private const string PASS = "password";
    private const string SOURCE = "data source";
    private const string CATALOG = "catalog";
    private const string SIZE = "size";

    private const string SECTION = "DataBase";
    private static string INI_FILE = System.Environment.GetEnvironmentVariable("WINDIR") + "\\eii.ini";
    // @"C:\Winnt\system32\ini.dll";

    [DllImport("kernel32")]
    private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
    [DllImport("kernel32")]
    private static extern uint GetPrivateProfileInt(string section, string key, uint size, string filePath);
    public SQLConnString()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    /// <summary>
    /// 取得web程序的数据库连接字符串
    /// </summary>
    /// <returns></returns>
    private static string GetConnStrWeb()
    {
        return ConfigurationSettings.AppSettings["Tiny_Dust_DL_DataBase_Conn_String"];
    }

    /// <summary>
    /// 取得CS程序的连接字符串
    /// </summary>
    /// <returns></returns>
    private static string GetConnStrDeskTop()
    {
        string ReturnText;
        ReturnText = "persist security info=False; packet size=" + GetPrivateProfileInt(SECTION, SIZE, 4096, INI_FILE).ToString() + ";data source=" + IniReadValue(SOURCE)
            + ";initial catalog=" + IniReadValue(CATALOG) + ";user id="
            + IniReadValue(USER) + ";password=" + IniReadValue(PASS);
        // ReturnText="provider=SQLOLEDB;data source=172.16.36.222"+
        // ";initial catalog=RemoteEdu;user id=sa"
        // +";password=1234567890";

        return ReturnText;
    }

    /// <summary>
    /// 取得连接字符串
    /// </summary>
    /// <returns></returns>
    public static string GetConnStr()
    {
#if WEB
        return GetConnStrWeb();
#else
        return GetConnStrDeskTop();
#endif
    }

    /// <summary>
    /// 从配置文件中取配置
    /// </summary>
    /// <param name="Key"></param>
    /// <returns></returns>
    public static string IniReadValue(string Key)
    {
        StringBuilder temp = new StringBuilder(255);
        int i = GetPrivateProfileString(SECTION, Key, "", temp, 255, INI_FILE);
        return temp.ToString();
    }
}

回复人: wushengshan(wushengshan) ( 一级(初级)) 信誉:100 2003-9-1 12:10:22 得分:0

当读取中文内容时读出来的是乱码,谁能帮我看看!下面是我的代码:

OpenFileDialog fileName = new OpenFileDialog();
fileName.ShowDialog();
StreamReader sr = File.OpenText(fileName.FileName);
string str;

//str = sr.ReadToEnd();
while((str = sr.ReadLine()) != null)
{
    textBox1.AppendText(str);
}

回复人: gujianxin(木头象) ( 五级(中级)) 信誉:100 2003-9-1 13:54:39 得分:0

StreamReader sr = new StreamReader(@"c:\test1.txt",System.Text.Encoding.GetEncoding("GB2312"));

回复人: xixigongzhu(夕夕公主) ( 一星(中级)) 信誉:105 2003-9-1 17:26:31 得分:1

默认的编码是UTF8。
这样试试:

OpenFileDialog fileName = new OpenFileDialog();
fileName.ShowDialog();
StreamReader sr = new StreamReader(fileName.FileName, Encoding.GetEncoding("gb2312"));
string str;

//str = sr.ReadToEnd();
while((str = sr.ReadLine()) != null)
{
    textBox1.AppendText(str);
}

回复人: wkyjob(流星划過...) ( 二级(初级)) 信誉:100 2003-9-12 15:30:41 得分:14

写:

StreamWriter sw = File.CreateText(@"d:\a.txt");
sw.Write("KK:");
sw.WriteLine(textBox1.Text);
sw.Close();

读:

StreamReader sr = File.OpenText(@"d:\a.txt");
string str;
while((str = sr.ReadLine()) != null)
{
    textBox2.Text = str;
}
Contributors: FHL