C#对文件的操作

小记怡情

public static class FileHelper
{
    /// <summary>
    /// 判断文件是否存在
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public static bool JudgeFileExist(string path)
    {
        if (string.IsNullOrEmpty(path))
        {
            return false;
        }
        return File.Exists(path);
    }

    /// <summary>
    /// 创建文件
    /// </summary>
    /// <param name="path"></param>
    public static void CreateFile(string path)
    {
        if (string.IsNullOrEmpty(path))
        {
            return;
        }
        try
        {
            File.Create(path);
        }
        catch
        {
            // About 是我自定义的弹窗
            App.Current.Dispatcher.Invoke((Action)(() => { new About("提示", "", "路径格式不正确!",false).ShowDialog(); }));
            //MessageBox.Show("路径格式不正确。");
        }
    }

    /// <summary>
    /// 从txt文件中读取数据
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public static string GetStringFromTXT(string path)
    {
        try
        {
            if (string.IsNullOrEmpty(path))
            {
                return string.Empty;
            }
            using (StreamReader sr = new StreamReader(path))
            {
                return sr.ReadToEnd();
            }
        }
        catch (Exception)
        {
            return string.Empty;
        }
        
    }
    /// <summary>
    /// 根据路径删除文件
    /// </summary>
    /// <param name="path"></param>
    public static void DeleteFile(string path)
    {
        FileAttributes attr = File.GetAttributes(path);
        if (attr == FileAttributes.Directory)
        {
            Directory.Delete(path, true);
        }
        else
        {
            File.Delete(path);
        }
    }
    public static void WriteIntoTXT(string path, string data)
    {
        using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
        {
            //获得字节数组
            byte[] dataByte = Encoding.Default.GetBytes(data);
            //开始写入
            fs.Write(dataByte, 0, data.Length);
            //清空缓冲区、关闭流
            fs.Flush();
            fs.Close();
        }
    }

    public static string GetFileNameByPathWithExtension(string path)
    {
        string name = string.Empty;
        if (!string.IsNullOrEmpty(path))
        {
            name = path.Substring(path.LastIndexOf("\\") + 1);
        }
        return name;
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值