开启辅助访问 切换到宽版

精易论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

用微信号发送消息登录论坛

新人指南 邀请好友注册 - 我关注人的新帖 教你赚取精币 - 每日签到


求职/招聘- 论坛接单- 开发者大厅

论坛版规 总版规 - 建议/投诉 - 应聘版主 - 精华帖总集 积分说明 - 禁言标准 - 有奖举报

查看: 2018|回复: 8
收起左侧

[C#图文教程] 易转C# - 8 - File文件读写

[复制链接]
结帖率:95% (84/88)
发表于 2023-8-14 00:48:55 | 显示全部楼层 |阅读模式   泛播地址
本帖最后由 陽陽陽 于 2023-8-14 00:51 编辑

直接上代码,里面带着注释:

using System;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Threading;

namespace FileExample
{
    class Program
    {
        static void Main(string[] args)
        {
            //string text = "{";
            //for (int i = 0; i < 100; i++)
            //{
            //    text += "9,";
            //}
            //Console.WriteLine(text);
            //StreamWriterExample();
            StringToArrayExample();


            //SeekExample();
        }
        public static void StringToArrayExample()
        {
            //GZipStream gZip = new GZipStream();
            string text = "我tm是一段文本 - 234241q24q34";
            byte[] arr = Encoding.UTF8.GetBytes(text);
            //foreach (byte i in arr)
            //{
            //    Console.WriteLine(Convert.ToChar(i)); //中文占2字符,正常现象
            //}

            foreach (byte b in text)
            {
                Console.WriteLine(b);
            }

            //两种方法自己选择

            //String - 一段文本
            //Char - 一个文本(中文占2个Char)
            //byte - 一个无符号的8位整数,用于写入数据


            //--------------------------------分割线--------------------------------
            //--------------------------------分割线--------------------------------
            //--------------------------------分割线--------------------------------

            //在UTF-8编码中,一个中文字符通常占用3个字节。
            //在GB2312或GBK编码中,一个中文字符占用2个字节。
            //在UTF-16编码中,一个中文字符占用2个字节。
            //在UTF-32编码中,一个中文字符占用4个字节。
            //- New Bing

        }


        [Obsolete("警告:此方法严重难用,建议直接弃用,并改用为ZIPFileExample")]
        public static void GZIPExample()
        {
            byte[] br = { 1, 2, 3, 4, 5 };
            using (FileStream filestream = new FileStream("GZIPexample2.txt", FileMode.Create, FileAccess.ReadWrite))
            {
                using (GZipStream gZipStream = new GZipStream(filestream, CompressionMode.Compress))
                {
                    gZipStream.Write(br,0,br.Length);
                    //using (StreamWriter sw = new StreamWriter(gZipStream))
                    //{
                    //    sw.Write(br);
                    //}
                    //当您使用 StreamWriter 类的 Write 方法将字节数组写入流中时,它会先将字节数组转换为字符串。这个转换过程是通过使用默认编码(UTF-8)来完成的。由于编码转换会改变数据的表示方式,所以这个转换过程会改变原始字节数组的内容。

                    //这种改变对数据有影响。在您的例子中,由于您使用了 StreamWriter 类来将字节数组转换为字符串,然后再写入 GZipStream,所以写入文件的数据与原始字节数组不同。

                    //如果您希望保留原始字节数组的内容,那么您应该直接使用 GZipStream 的 Write 方法来写入数据,而不是使用 StreamWriter 类。这样,您就可以避免在写入过程中对数据进行任何转换,从而保留原始字节数组的内容。


                    //我管nmb什么相同不相同,好用才是王道
                }
            }

            using (FileStream filestream = new FileStream("GZIPexample2.txt", FileMode.Open, FileAccess.ReadWrite))
            {
                using (GZipStream gZipStream = new GZipStream(filestream, CompressionMode.Decompress))
                {
                    long length = filestream.Length;
                    byte[] arr = new byte[length];
                    gZipStream.Read(arr,0,(int)length);




                    //大坑!!!无法确认解压后多大,这数组是解压前的大小,建议直接把这个方法弃用!!!!!!






                    foreach (var i in arr)
                    {
                        Console.WriteLine(i);
                    }
                    //using (StreamReader reader = new StreamReader(gZipStream))
                    //{

                    //    string data = reader.ReadToEnd();
                    //    byte[] byteArray = Encoding.UTF8.GetBytes(data);
                    //    foreach (var i in byteArray)
                    //    {
                    //        Console.WriteLine(i);
                    //    }
                    //}
                    //↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑这种方法不好用,建议直接弃用↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

                }
            }
        }
        public static void ZIPFileExample()
        {
            Directory.CreateDirectory("ZIPFileExample");
            Directory.CreateDirectory("ZIPFileExampleExtract");


            File.WriteAllText("./ZIPFileExample/1.txt","This is a txt file");
            ZipFile.CreateFromDirectory("ZIPFileExample","1.zip");
            ZipFile.ExtractToDirectory("1.zip", "ZIPFileExampleExtract");
        }
        public static void SetLengthExample()
        {
            using (FileStream fileStream = new FileStream("example.txt", FileMode.OpenOrCreate))
            {
                fileStream.SetLength(70); //包含第70个
                //fileStream.Seek();
            }

        }
        public static void EncryptExample()
        {
            //System.IO.File.Encrypt();
            //↑↑↑↑↑↑↑↑↑↑↑↑
            //↑↑↑↑↑↑↑↑↑↑↑↑
            //就这个方法,不支持跨平台,安全性还低,同一个账号登录直接破解
            //直接r4c加密就好了,没必要用这个方法

            //System.IO.File.Decrypt();
            //↑↑↑↑↑↑↑↑↑↑↑↑
            //解密
        }
        public static void FileExistsExample()
        {
            Console.WriteLine(File.Exists("https://getsamplefiles.com/download/txt/sample-1.txt"));
            //必须要以共享的方式才能判断,这样判断不行


            FileInfo fileInfo = new FileInfo("https://getsamplefiles.com/download/txt/sample-1.txt");
            Console.WriteLine(fileInfo.Exists);
        }
        public static void FileStreamWriteAllByte()
        {
            string filePath = "example.txt";
            //byte[] content = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
            //byte[] content = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
            //    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
            //    34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
            //    53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
            //    72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
            //    91, 92, 93, 94, 95, 96, 97, 98, 99 };



            byte[] content = new byte[] { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
                9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
                9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
                9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
                9, 9, 9, 9, 9 };
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                fs.Write(content, 0, content.Length);
            }
        }
        public static void SeekExample()
        {
            using (FileStream fileStream = new FileStream("example.txt", FileMode.Open))
            {
                fileStream.Seek(6, SeekOrigin.Begin);
                byte[] b = { 6, 6, 6 };
                fileStream.Write(b, 0, b.Length); //从第六个位置开始,包含第六个
            }
        }
        public static async void FileStreamExaple()
        {
            using (FileStream fst = new FileStream("example.txt", FileMode.OpenOrCreate))
            {
                CancellationToken ct = new CancellationToken();
                byte[] content = new byte[] { 1, 4, 4, 2 };


                //fst.Write(content, 0, content.Length);
                await fst.WriteAsync(content, 0, content.Length, ct); //off会覆盖



                fst.Flush(); //立刻写入磁盘,不等待缓冲区变满

                fst.Close();


                //fst.Dispose();//释放使用的所有资源
                //在底层代码中,close包含了dispose
                //即使用了using代码,还是建议加上close()
                //https://stackoverflow.com/questions/7524903/should-i-call-close-or-dispose-for-stream-objects

            }
        }
        public static void StreamWriterExample()
        {
            using (StreamWriter fst = File.CreateText("example2.txt"))
            {
                fst.WriteLine("1234567");
                fst.Close();
            }
        }
        public static void AccessTimeExample()
        {
            DateTime dt = new DateTime(2003, 2, 3, 5, 30, 43, DateTimeKind.Utc);

            File.GetLastAccessTime("example.txt");
            File.SetLastAccessTime("example2.txt", DateTime.Now);
        }
    }
}




顺便推荐本书:https://libgen.su/book/index.php ... 3FE4B8F84D6B2D53732
(需要魔法+洋葱)

Title:Beginning C# and .NETVolume:
Author(s):Benjamin Perkins, Jon D. Reid


结帖率:95% (84/88)

签到天数: 11 天

 楼主| 发表于 2023-8-21 06:30:39 | 显示全部楼层   泛播地址
补充下FileWatcher:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FileWatcherTest
{
    public partial class Form1 : Form
    {
        public static FileSystemWatcher watcher = new FileSystemWatcher();
        public static Random rd = new Random();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FileWatcherExample();
            Thread.Sleep(5000);
            using (File.Create("watcher/" + rd.Next(1, 3333) + ".txt")) { };
            Thread.Sleep(5000);
            watcher.EnableRaisingEvents = false;
            using (File.Create("watcher/" + rd.Next(1, 3333) + ".txt")) { };

        }
        public static void FileWatcherExample()
        {
            Directory.CreateDirectory("watcher");
            
            watcher.BeginInit(); //开始声明
            watcher.Path = "watcher";
            watcher.Deleted += (s, e) => { MessageBox.Show("deleted"); };
            watcher.Created += (s, e) => { MessageBox.Show("created"); };
            watcher.Changed += (s, e) => { MessageBox.Show(e.ChangeType.ToString()); };



            watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size;


            watcher.EndInit(); //完成声明

            watcher.EnableRaisingEvents = true;




        }

    }
}

记得用.net framwork,.net core的话需要进程一直存在。
可以试试while(true) + Thread.Sleep()

点评

此外,枚举可以用Directory.GetFiles()   泛播地址  发表于 2023-8-21 06:31
回复 支持 反对

使用道具 举报

签到天数: 11 天

发表于 2023-8-28 13:36:36 | 显示全部楼层   浙江省金华市
C# 除了反编译和啰嗦  其他都是优点
回复 支持 反对

使用道具 举报

结帖率:0% (0/1)

签到天数: 1 天

发表于 2023-8-24 11:06:06 | 显示全部楼层   河南省洛阳市
有这么麻烦吗?
回复 支持 反对

使用道具 举报

签到天数: 4 天

发表于 2023-8-16 08:31:01 | 显示全部楼层   江苏省苏州市
C#比易语言更高效的,支持下
回复 支持 反对

使用道具 举报

结帖率:40% (4/10)
发表于 2023-8-14 16:20:54 高大上手机用户 | 显示全部楼层   安徽省合肥市
666666666666666666
回复 支持 反对

使用道具 举报

结帖率:78% (7/9)

签到天数: 2 天

发表于 2023-8-14 10:54:05 | 显示全部楼层   广东省东莞市
花老板 发表于 2023-8-14 10:20
楼主是在表达,易语言2句代码的事情,C#需要200句代码。

这不扯淡吗,易不封装的话不照样需要大量代码,封装的话所有语言不都一样

评分

参与人数 1好评 +1 精币 +3 收起 理由
陽陽陽 + 1 + 3 感谢分享,很给力!~

查看全部评分

回复 支持 反对

使用道具 举报

结帖率:96% (87/91)

签到天数: 13 天

发表于 2023-8-14 10:20:37 | 显示全部楼层   湖北省十堰市
楼主是在表达,易语言2句代码的事情,C#需要200句代码。

评分

参与人数 1好评 +1 精币 +3 收起 理由
陽陽陽 + 1 + 3 正解,哈哈哈哈

查看全部评分

回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 致发广告者

发布主题 收藏帖子 返回列表

sitemap| 易语言源码| 易语言教程| 易语言论坛| 易语言模块| 手机版| 广告投放| 精易论坛
拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论,本站内容均为会员发表,并不代表精易立场!
论坛帖子内容仅用于技术交流学习和研究的目的,严禁用于非法目的,否则造成一切后果自负!如帖子内容侵害到你的权益,请联系我们!
防范网络诈骗,远离网络犯罪 违法和不良信息举报电话0663-3422125,QQ: 793400750,邮箱:wp@125.la
Powered by Discuz! X3.4 揭阳市揭东区精易科技有限公司 ( 粤ICP备12094385号-1) 粤公网安备 44522102000125 增值电信业务经营许可证 粤B2-20192173

快速回复 返回顶部 返回列表