chr
2024-10-09 1f645778ae80a3a8801b8bb4d0fcf8feb244ad43
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace PdmSwPlugin.Common.Util
{
    public class BinUtil
    {
        /// <summary>
        /// 把明文密码加密后以二进制存入bin文件中
        /// TODO 使用机器码加密
        /// </summary>
        /// <param name="content">字符内容</param>
        /// <param name="filePath">存放路径</param>
        public static void SaveStrToBin(string content, string filePath = null)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().FullName), "bin");
            }
            byte[] bytes = Convert.FromBase64String(content);
            using (Stream stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            using (BinaryWriter writer = new BinaryWriter(stream))
            {
                writer.Write(bytes);
            }
        }
 
        /// <summary>
        /// 从bin中加载字符串
        /// </summary>
        /// <param name="content">字符串内容</param>
        /// <param name="filePath">bin文件路径</param>
        /// <returns>读取是否成功</returns>
        public static bool LoadStrFromBin(ref string content, string filePath = null)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().FullName), "bin");
            }
            if (!File.Exists(filePath))
            {
                return false;
            }
            using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            using (BinaryReader reader = new BinaryReader(stream))
            {
                byte[] bytes = new byte[stream.Length];
                reader.Read(bytes, 0, bytes.Length);
                content = Convert.ToBase64String(bytes);
                return true;
            }
        }
    }
}