C#如何将one.txt的内容读取并将该内容写到另一个two.txt中

编程入门 行业动态 更新时间:2024-10-27 12:24:06

C#如何将one.txt的<a href=https://www.elefans.com/category/jswz/34/1771374.html style=内容读取并将该内容写到另一个two.txt中"/>

C#如何将one.txt的内容读取并将该内容写到另一个two.txt中

说明:

  1. 在网上你可以找到很多读文件或者写文件,但一般的博主都是分开讲,在写文件方面更多的是写入一个字符串。

  2. 在本篇博文中,我们关注的是如何将一个txt的内容读取到,再将他写入到另一个txt

需求:

  1. 读取F盘中log.txt 文件
  2. 将文件的内容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中

本文发布于:2024-03-08 19:36:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1722072.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内容   写到   将该   如何将   txt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!