C# 写入、读取文本内容

 

写入操作必须要有该路径的目录,若没有目录将无法进行写入。而对应的文件若没有,会自动的创建。

1、写入读取文本的方法

// **************** 写入内容 *******************
//向指定路径添加文件,不会覆盖原有内容
AppendAllText(String, String)
//向指定路径添加内容,会覆盖之前的内容。所添加的内容全部在同一行
WriteAllText(String, String)
//向指定路径添加内容,会覆盖之前的内容。字符串数组的每个元素作为一行
WriteAllLines(String, String[])


// ***************** 读取内容 ********************
//读取文件中的所有内容,作为一个字符串
ReadAllText(String)
//读取文件的所有行,返回一个数组,每行内容作为数组的一个元素
ReadAllLines(String)

2、写入实例:

using System;
using System.IO;

namespace WriteFile
{
    class Program
    {
        static void Main(string[] args)
        {
            string path01 = @"E:\Coding\RecordData\Data01";
            string path02 = @"E:\Coding\RecordData\Data02";

            string strPath01 = @"E:\Coding\RecordData\Data01\test01.txt";
            string strPath02 = @"E:\Coding\RecordData\Data02\test02.txt";

            string content01 = "this  is test for write files 1 2 3 4 5 6 7 7 8 9";
            string[] content02 = { "hello", "this", "just", "a", "test","for it." };

            // 判读是否存在该目录
            if (!Directory.Exists(path01))
            {
                Directory.CreateDirectory(path01);
            }
            if (!Directory.Exists(path02))
            {
                Directory.CreateDirectory(path02);
            }

            // 将内容添加到指定的文本中,不会覆盖已有的内容,在文本末尾接着添加
            File.AppendAllText(strPath01, content01 + Environment.NewLine);
            // 将内容写入到指定的文件中,会覆盖原有的内容
            File.WriteAllText(strPath01, content01);

            // 将字符串的所有内容都写入指定路径,字符串的每个元素作为一行
            File.WriteAllLines(strPath02, content02);


        }
       
    }

}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值