【C#】文件操作

创建文件夹

if (!Directory.Exists(desPath))
{
    try
    {
        Directory.CreateDirectory(desPath);
    }
    catch (Exception e)
    {
        throw new Exception("创建目标目录失败:" + e.Message);
    }
}

创建文件

using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath))
{
    JObject jobject = JObject.Parse(json);
    file.Write(jobject.ToString());
}

读取文件夹中所有指点文件目录

List<string> fileNameList = new List<string>();
try
{
    DirectoryInfo directoryInfo = new DirectoryInfo(folder);
    FileInfo[] files = directoryInfo.GetFiles("*.json");

    foreach (var item in files)
    {
        fileNameList.Add(item.Name);
    }
}
catch (Exception e)
{
    throw new Exception("获取文件路径错误:" + e.Message);
}
return fileNameList;

复制文件

try
{
    //filepath需要被复制的文件路径;desFile复制文件的目标路径;是否重写
    File.Copy(filepath, desFile, true);
}
catch (Exception e)
{
    Debug.Log($"复制文件 {filepath_full} 失败:" + e.Message);
}

读取文件

使用Using保证文件读取之后,文件流被关闭,防止进程占用

string filePath = folderPath + "/" + item;
using (StreamReader file = File.OpenText(filePath))
using (JsonTextReader reader = new JsonTextReader(file))
{
    JObject res = (JObject)JToken.ReadFrom(reader);
}

删除文件夹

删除文件时,出现报错:文件在其他进程被占用,检查创建/打开文件时,是否关闭文件流

if (Directory.Exists(folderPath))
{
    try
    {
        //删除文件夹,即使是空文件夹,也会被删除
        Directory.Delete(folderPath, true);

    }
    catch (Exception e)
    {
        string str = "errer :" + e.Message;
        throw new Exception(str);
    }
}

删除文件夹中的指定文件

if (Directory.Exists(folderPath))
{
    DirectoryInfo direction = new DirectoryInfo(folderPath);
    FileInfo[] files = direction.GetFiles("*", SearchOption.AllDirectories);
    for (int i = 0; i < files.Length; ++i)
    {
        if (files[i].Name.Contains(".json") || files[i].Name.Contains(".xml"))
        {
            File.Delete(folderPath + "/" + files[i].Name);
        }
    }
}

获取某格式的所有文件名

private List<string> GetAllFilesName(string folder)
{
    List<string> fileNameList = new List<string>();
    try
    {
        IsWrong = false;
        DirectoryInfo directoryInfo = new DirectoryInfo(folder);
        FileInfo[] files = directoryInfo.GetFiles("*.json");

        foreach (var item in files)
        {
            fileNameList.Add(item.Name);
        }
    }
    catch (Exception ex)
    {
        IsWrong = true;
        MessageBox.Show("获取文件路径错误\n" + ex);
    }
    return fileNameList;
}

读取TxT文本

Read 逐个字符读

ReadLine逐行读

ReadToEnd从头读到尾

private List<string> ReadTxtFile(string folder, string fileName){
    List<string> res = new List<string>();
    string filePath = System.IO.Path.Combine(folder + "/" + fileName);
    using (StreamReader sr = new StreamReader(txtfilePath, System.Text.Encoding.UTF8)){
        string line;
        while((line==sr.ReadLine())!=null){
            res.Add(line);
        }
        sr.Close();
    }
    return res;
}

写入TxT文本

Write 写入

WriteLine写入,并在最后加入换行符“\r\n”

Flush 清理缓冲区,并将缓冲区输入存入文件

StreamWriter (string path) 写入的新内容将替代原本的内容

StreamWriter ( string path, bool append ) append=true是追加内容

private void WriteTxtFile(string folder, string fileName, List<string> contents){
    string filePath = System.IO.Path.Combine(folder + "/" + fileName);
    using (StreamWriter sw = new StreamWriter(txtfilePath, System.Text.Encoding.UTF8)){
        foreach(var content in contents){
            sw.WriteLine(content);
        }
        sw.Flush();
        sw.Close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值