一:文件读取

filestream读取:

public void reader()

{

string s = "";
            FileStream file = new FileStream(@"d://shop_category[1].txt", FileMode.Open);
            StreamReader reader = new StreamReader(file,Encoding.Default);
            while (reader.ReadLine() != null)
            {
                s += reader.ReadLine();

            }

Console.WriteLine(s);

}

StreamReader

public void read()

{

FileStream file = new FileStream(@"d:\\sa.txt", FileMode.Open);
            byte[] bt = new byte[file.Length];
            file.Read(bt, 0, bt.Length);
            string str = Encoding.Default.GetString(bt);
conso.writeline(str);

}

public void read()

{

string s = File.ReadAllText(@"d://shop_category[1].txt",Encoding.Default);
            Console.WriteLine(s);

}

======================================================================

二:文件写入

public void writer()

{

string s="hello word";

FileStream write = new FileStream(@"d://aasdaaaaaa.txt", FileMode.Create);
            StreamWriter writer = new StreamWriter(write, Encoding.Default);
            writer.Write(s);
            Console.WriteLine(s);

}

将文字写入sa.txt

public void writer()

{

string s="hello word";

 File.WriteAllText(@"d://sa",s);

}

 /// <summary>
    /// 用FileStream写文件
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>

     public void FileStreamWriteFile(string str)
       {
         byte[] byData;
         char[] charData;
         try
             {
             FileStream nFile = new FileStream("love.txt", FileMode.Create);
             //获得字符数组
             charData = str.ToCharArray();
            //初始化字节数组
             byData = new byte[charData.Length];
             //将字符数组转换为正确的字节格式
             Encoder enc = Encoding.UTF8.GetEncoder();
             enc.GetBytes(charData, 0, charData.Length,byData,0,true);
             nFile.Seek(0, SeekOrigin.Begin);
             nFile.Write(byData, 0, byData.Length);
         }

         catch (Exception ex)
            {
             throw ex;
        }

    }

===============================================================

filesteam  读取

FileStream filestream = new FileStream(m_filepath, FileMode.Open, FileAccess.Read);
                StreamReader objStreamReader = new StreamReader(filestream);


                    while (objStreamReader.Peek()>=0)
                    {
                        string sLine = objStreamReader.ReadLine();//读取一行
        //可以将内容读到 ArrayList 中。
                    }

                    objStreamReader.Close();
                    filestream.Close();

 FileStream file = new FileStream(@"d:\\sa.txt", FileMode.Open); //读取sa.txt文件

            byte[] bt = new byte[file.Length];
            file.Read(bt, 0, bt.Length);  //转换为字节读取
            string str = Encoding.Default.GetString(bt);   //读到内存str中(可设置编码)

==============================================================

posted on 2011-02-18 15:18  高兴happy  阅读(215)  评论(0编辑  收藏  举报