C#基础:读取和写入txt文档

以下是控制台程序:

using DocumentFormat.OpenXml.ExtendedProperties;
using System;
using System.IO;
class ReadAndWriteTxt
{
    public string textContent {  get; set; }
    public List listContent { get; set; } = new List();
}
class Program
{
    public static ReadAndWriteTxt ReadTxt(string filePath)
    {
        ReadAndWriteTxt result = new ReadAndWriteTxt();
        try
        {
            result.textContent = File.ReadAllText(filePath);// 读取文本(字符串)
            result.listContent = result.textContent.Split().Where(x => !string.IsNullOrEmpty(x)).ToList();//读取文本(列表)
            return result;
        }
        catch (Exception ex)
        {
            result.textContent = ex.Message;
            return result;
        }
    }

    static void Main()
    {
        //一、txt读取
        string filePath = "F:\\C_program\\test2\\files\\文档.txt";
        ReadAndWriteTxt result = ReadTxt(filePath);
        Console.WriteLine(result.textContent);//打印文本(字符串)
        Console.WriteLine(string.Join('\n',result.listContent));//打印文本(列表)

        //二、txt写入(纯字符串)
        string filePath2 = "F:\\C_program\\test2\\files\\文档2.txt";
        var content = "写入的内容";
        File.WriteAllText(filePath2, content);

        //三、txt写入(字符串列表)
        string filePath3 = "F:\\C_program\\test2\\files\\文档3.txt";
        List lines = new List
        {
            "第一行内容",
            "第二行内容",
            "第三行内容"
        };
        File.WriteAllLines(filePath3, lines);
    }
}

你可能感兴趣的:(C#基础,c#,开发语言)