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.");
    }
}
相关推荐
SmalBox8 小时前
【URP】UnityHLSL顶点片元语义详解
unity·渲染
在路上看风景19 小时前
9. Mono项目与Unity的关系
unity
在路上看风景20 小时前
1.12 Memory Profiler Package - Summary
unity
xiaowu0801 天前
策略模式-不同的鸭子的案例
开发语言·c#·策略模式
VisionPowerful1 天前
九.弗洛伊德(Floyd)算法
算法·c#
ArabySide1 天前
【C#】 资源共享和实例管理:静态类,Lazy<T>单例模式,IOC容器Singleton我们该如何选
单例模式·c#·.net core
SmalBox1 天前
【URP】Unity Shader Tags
unity·渲染
gc_22991 天前
C#测试调用OpenXml操作word文档的基本用法
c#·word·openxml
almighty271 天前
C#海康车牌识别实战指南带源码
c#·海康车牌识别·c#实现车牌识别·车牌识别源码·c#车牌识别
极客柒1 天前
Unity 塔防自用可视化路点寻路编辑器
unity·编辑器·游戏引擎