// 寫操作
public static void Write()
{
// 統(tǒng)計(jì)寫入(讀取的行數(shù))
int WriteRows = 0;
// 讀取文件的源路徑及其讀取流
string strReadFilePath = @"..\..\data\ReadLog.txt";
StreamReader srReadFile = new StreamReader(strReadFilePath);
// 寫入文件的源路徑及其寫入流
string strWriteFilePath = @"..\..\data\WriteLog.txt";
StreamWriter swWriteFile = File.CreateText(strWriteFilePath);
// 讀取流直至文件末尾結(jié)束,并逐行寫入另一文件內(nèi)
while (!srReadFile.EndOfStream)
{
string strReadLine = srReadFile.ReadLine(); //讀取每行數(shù)據(jù)
++WriteRows; //統(tǒng)計(jì)寫入(讀?。┑臄?shù)據(jù)行數(shù)
swWriteFile.WriteLine(strReadLine); //寫入讀取的每行數(shù)據(jù)
Console.WriteLine("正在寫入... " + strReadLine);
}
// 關(guān)閉流文件
srReadFile.Close();
swWriteFile.Close();
Console.WriteLine("共計(jì)寫入記錄總數(shù):" + WriteRows);
Console.ReadKey();
}
========================================================================
完整源代碼(經(jīng)過本人測試,直接運(yùn)行就可)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO; // 引用輸入輸出操作的命令空間
namespace ReadWriteFile
{
class Program
{
// 主函數(shù)
static void Main(string[] args)
{
Read(); // 讀操作
Write(); // 寫操作
}
// 讀操作
public static void Read()
{
// 讀取文件的源路徑及其讀取流
string strReadFilePath = @"..\..\data\ReadLog.txt";
StreamReader srReadFile = new StreamReader(strReadFilePath);
// 讀取流直至文件末尾結(jié)束
while (!srReadFile.EndOfStream)
{
string strReadLine = srReadFile.ReadLine(); //讀取每行數(shù)據(jù)
Console.WriteLine(strReadLine); //屏幕打印每行數(shù)據(jù)
}
// 關(guān)閉讀取流文件
srReadFile.Close();
Console.ReadKey();
}
// 寫操作
public static void Write()
{
// 統(tǒng)計(jì)寫入(讀取的行數(shù))
int WriteRows = 0;
// 讀取文件的源路徑及其讀取流
string strReadFilePath = @"..\..\data\ReadLog.txt";
StreamReader srReadFile = new StreamReader(strReadFilePath);
// 寫入文件的源路徑及其寫入流
string strWriteFilePath = @"..\..\data\WriteLog.txt";
StreamWriter swWriteFile = File.CreateText(strWriteFilePath);
// 讀取流直至文件末尾結(jié)束,并逐行寫入另一文件內(nèi)
while (!srReadFile.EndOfStream)
{
string strReadLine = srReadFile.ReadLine(); //讀取每行數(shù)據(jù)
++WriteRows; //統(tǒng)計(jì)寫入(讀取)的數(shù)據(jù)行數(shù)
swWriteFile.WriteLine(strReadLine); //寫入讀取的每行數(shù)據(jù)
Console.WriteLine("正在寫入... " + strReadLine);
}
// 關(guān)閉流文件
srReadFile.Close();
swWriteFile.Close();
Console.WriteLine("共計(jì)寫入記錄總數(shù):" + WriteRows);
Console.ReadKey();
}
}
}