C#读取和写入txt文档(在unity中示例)

本篇内容简单介绍如何在c#中内容读取和写入txt文档

注意:先在Unity的StreamingAssets文件夹中创建一个txt文档

一、读取txt

1.1全部一起读取

cs 复制代码
private void ReadText01()
{
    string filePath = Path.Combine(Application.streamingAssetsPath, "testTXT.txt");
    // 读取文件内容
    if (File.Exists(filePath))
    {
        string fileContent = File.ReadAllText(filePath);
        Debug.Log(fileContent); // 输出文件内容
    }
    else
    {
        Debug.LogError("文件不存在: " + filePath);
    }
}

1.2全部逐行读取

cs 复制代码
private void ReadText02()//逐行读取
{
    string filePath2 = Path.Combine(Application.streamingAssetsPath, "testTXT.txt");
    // 读取文件内容
    if (File.Exists(filePath2))
    {
        using (StreamReader reader = new StreamReader(filePath2))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Debug.Log(line); // 输出每一行内容
            }
        }
    }
    else
    {
        Debug.LogError("文件不存在: " + filePath2);
    }
}

二、写入txt

2.1全部一起写入(删除旧内容,添加新内容)

cs 复制代码
 private void WriteTxt01()//全部写入
 {
     string filePath3 = Path.Combine(Application.streamingAssetsPath, "testTXT.txt");
     // 要写入的内容
     string contentToWrite = "方法1小文件写入txt";
     // 写入文件内容
     File.WriteAllText(filePath3, contentToWrite);
 }

2.2全部逐行写入(删除旧内容,添加新内容)

cs 复制代码
private void WriteTxt02()//逐行写入
{
    string filePath4 = Path.Combine(Application.streamingAssetsPath, "testTXT.txt");
    // 要写入的内容
    string contentToWrite2 = "Hello, this is a test message.\nThis is a new line.";
    // 使用 StreamWriter 写入文件内容
    using (StreamWriter writer = new StreamWriter(filePath4))
    {
        writer.WriteLine(contentToWrite2); // 写入内容
    }
}

2.3全部一起写入(不删除旧内容情况下直接添加新内容)

cs 复制代码
private void WriteTxt01()//全部写入
{
    string filePath3 = Path.Combine(Application.streamingAssetsPath, "testTXT.txt");
    // 要写入的内容
    string contentToWrite = "方法1小文件写入txt";
    // 追加文件内容
    File.AppendAllText(filePath3, contentToWrite);
}

2.4全部逐行写入(不删除旧内容情况下直接添加新内容)

cs 复制代码
private void WriteTxt02()//支持逐行写入
{
    // 设置文本文件的路径(在 Unity 的 StreamingAssets 文件夹中)
    string filePath4 = Path.Combine(Application.streamingAssetsPath, "testTXT.txt");

    // 要写入的内容
    string contentToWrite2 = "Hello, this is a test message.\nThis is a new line.";
    using (StreamWriter writer2 = new StreamWriter(filePath4, true))
    {
        writer2.WriteLine("This line will be appended.");
    }
}
相关推荐
开开心心就好2 小时前
高效Excel合并拆分软件
开发语言·javascript·c#·ocr·排序算法·excel·最小二乘法
一名用户4 小时前
unity实现自定义粒子系统
c#·unity3d·游戏开发
钢铁男儿6 小时前
C# 类和继承(扩展方法)
java·servlet·c#
爱炸薯条的小朋友6 小时前
C#由于获取WPF窗口名称造成的异常报错问题
windows·c#·wpf
不伤欣7 小时前
游戏设计模式 - 子类沙箱
游戏·unity·设计模式
Rose 使者8 小时前
全球IP归属地查询接口如何用C#进行调用?
c#·api·ip地址
~plus~10 小时前
Harmony核心:动态方法修补与.NET游戏Mod开发
开发语言·jvm·经验分享·后端·程序人生·c#
htj1010 小时前
C# 使用正则表达式
正则表达式·c#
~plus~10 小时前
WPF八大法则:告别模态窗口卡顿
开发语言·经验分享·后端·程序人生·c#
就是有点傻11 小时前
使用WPF的Microsoft.Xaml.Behaviors.Wpf中通用 UI 元素事件
c#