内容读取并将该内容写到另一个two.txt中"/>
C#如何将one.txt的内容读取并将该内容写到另一个two.txt中
说明:
在网上你可以找到很多读文件或者写文件,但一般的博主都是分开讲,在写文件方面更多的是写入一个字符串。
在本篇博文中,我们关注的是如何将一个txt的内容读取到,再将他写入到另一个txt
需求:
- 读取F盘中log.txt 文件
- 将文件的内容copy到F盘下的mylog.txt文件中,同时允许在该文件后追加
代码:
using System;
using System.Diagnostics;
using System.IO;
using System.Security;
using System.Text;namespace TestRw0730
{public class Program{public static void getContentToFile(String conpath){FileStream fs = null;StreamReader sr = null;StreamWriter sw = new StreamWriter(@"f:\\myLog.txt", true);try{String content = String.Empty;fs = new FileStream(conpath, FileMode.Open);sr = new StreamReader(fs);while ((content = sr.ReadLine()) != null){content = content.Trim().ToString();sw.WriteLine(content);}}catch{Console.WriteLine("读取内容到文件方法错误");}finally{if (fs != null){fs.Close();}if (sw != null){sw.Close();}}}static void Main(string[] args){String conpath = @"F:\log.txt";//定义要获取的文件内容地址getContentToFile(conpath);//将log.txt内容写入到自己的文件中`}
}
解释:
核心代码主要是以下这句:
while ((content = sr.ReadLine()) != null){content = content.Trim().ToString();sw.WriteLine(content);}
这的意思是:只要文件还有内容可以读取 {
我们就先将文件读取的内容去除空格后赋值给content
然后将content写入新的文件中
}
更多推荐
C#如何将one.txt的内容读取并将该内容写到另一个two.txt中
发布评论