Unity--System.IO文件操作

今天看到System.IO的一些教程,是对windows下文件或文件夹的增删改的操作。

已经写好了注释,按照注释一步步看就可以了。

using UnityEngine;
using System.Collections;
using System.IO;
 
public class Test : MonoBehaviour {
 
    void Start()
    {
        CreateFileAndDirector();
 
        WriteTextFile();
 
        ReadTextFile();
 
        CopyAndMoveFile();
    }
 
    /// <summary>
    /// 创建文件夹“MyTest”和文件“1.txt”
    /// </summary>
    void CreateFileAndDirector()
    {
        // 指定一个“当前活动文件夹”
        string activeDir = @"d:\";
 
        // 合并路径字符串 组合成:d:\MyTest
        string newPath = Path.Combine(activeDir, "MyTest");
 
        // 创建文件夹
        Directory.CreateDirectory(newPath);
 
        // 创建一个新文件的名字
        string newFileName = "1.txt";
 
        // 指定该文件位置
        newPath = Path.Combine(newPath, newFileName);
 
        // 创建文件
        if (!File.Exists(newPath))
        {
            File.Create(newPath);
        }
 
    }
 
    /// <summary>
    /// 写入文件
    /// </summary>
    void WriteTextFile()
    {
        string path = @"d:\MyTest\1.txt";
 
        string text = "A class is the most powerful data type in C#. Like structures, " +
                           "a class defines the data and behavior of the data type. ";
        // 不分行
        File.WriteAllText(path, text);
 
        string[] lines = { "First line", "Second line", "Third line" };
        // 写到三行
        File.WriteAllLines(@"d:\MyTest\1.txt", lines);
    }
 
    /// <summary>
    /// 读取文件
    /// </summary>
    void ReadTextFile()
    {
        // 读取所有内容
        string text = File.ReadAllText(@"d:\MyTest\1.txt");
        Debug.Log(text);
 
        // 分行读取所有内容
        string[] lines = File.ReadAllLines(@"d:\MyTest\1.txt");
        Debug.Log(lines[0]);
    }
 
    /// <summary>
    /// 复制和移动文件
    /// </summary>
    void CopyAndMoveFile()
    {
        string fileName = "1.txt";
 
        string sourcePath = @"d:\MyTest";
        string targetPath = @"d:\MyTest\SubDir";
 
 
        string sourceFile = Path.Combine(sourcePath, fileName);
        string destFile = Path.Combine(targetPath, fileName);
 
        if (!Directory.Exists(targetPath))
        {
            Directory.CreateDirectory(targetPath);
        }
 
        // 复制文件,TRUE为如果目标目录已存在该文件,则覆盖;FALSE已存在该文件 则取消复制
        File.Copy(sourceFile, destFile, true);
 
        // 移动文件
        //File.Move(sourceFile, destFile);
    }
}
转载自: 网虫虫 u3d8.com 发表过

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值