C# 文件与字节数组Bytes[]之间相互转换

 

C# 文件与字节数组Bytes[]之间相互转换

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
using System.IO;
  
namespace FileBytes
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] bytes = FileToBytes(@"D:\1.txt");
            if (bytes.Length > 0)
            {
                // 重新保存一份文件
                BytesToFile(bytes, @"D:\2.txt");
            }
  
            // 文件重新保存md5, sha1不变
        }
  
        /// <summary>
        /// 文件 -> Bytes
        /// </summary>
        /// <param name="path">指定路径文件</param>
        /// <returns>返回Stream</returns>
        public static byte[] FileToBytes(string path)
        {
            try
            {
                if (!System.IO.File.Exists(path)) { return new byte[0]; }
  
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    // 读取文件的 byte[]
                    byte[] bytes = new byte[fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    return bytes;
                }
            }
            catch
            {
                throw;
            }
        }
  
        /// <summary>
        /// Bytes -> 文件
        /// </summary>
        /// <param name="bytes">byte数组</param>
        /// <param name="path">保存地址</param>
        public static void BytesToFile(byte[] bytes, string path)
        {
            try
            {
                // 文件存在则删除
                if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); }
  
                // 写入文件,方式一
                using (FileStream fs = new FileStream(path, FileMode.CreateNew))
                {
                    using (BinaryWriter bw = new BinaryWriter(fs))
                    {
                        bw.Write(bytes, 0, bytes.Length);
                    }
                }
  
                // 写入文件,方式二
                //System.IO.File.WriteAllBytes(path, bytes);
            }
            catch
            {
                throw;
            }
        }
    }
}

 

posted @   funiyi816  阅读(1155)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示