欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > C#读取和写入txt文档(在unity中示例)

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

2026/1/31 20:31:26 来源:https://blog.csdn.net/cherry_f_f/article/details/142980156  浏览:    关键词:C#读取和写入txt文档(在unity中示例)

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

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

一、读取txt

1.1全部一起读取

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全部逐行读取

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全部一起写入(删除旧内容,添加新内容)

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

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

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全部一起写入(不删除旧内容情况下直接添加新内容)

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

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

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.");}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词