原文:https://www.cnblogs.com/xuxml/p/13946816.html
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
// 原文:https://www.cnblogs.com/xuxml/p/13946816.html
static void Main(string[] args)
{
DirectoryInfo dir = new DirectoryInfo("D:\\2021-02\\");
FileInfo[] allFile = dir.GetFiles();
foreach (FileInfo fInfo in allFile)
{
convertFile(fInfo.FullName);
}
}
static void convertFile(String path)
{
// var path = @"D:\9a064413d6f5d36cfbdc7d2263dbb7bb.dat";
byte[] byteArray = FileBinaryConvertHelper.File2Bytes(path);
Dictionary<byte, string> keyValuePairs = new Dictionary<byte, string>();
keyValuePairs.Add(0xFF, "jpg");
keyValuePairs.Add(0x89, "png");
keyValuePairs.Add(0x47, "gif");
byte sc = new byte();
byte tsc = new byte();
if ((byteArray[0] ^ 0xFF) == (byteArray[1] ^ 0xD8))
{
tsc = 0xFF;
sc = BitConverter.GetBytes(byteArray[0] ^ 0xFF)[0];
}
if ((byteArray[0] ^ 0x89) == (byteArray[1] ^ 0x50))
{
tsc = 0x89;
sc = BitConverter.GetBytes(byteArray[0] ^ 0x89)[0];
}
if ((byteArray[0] ^ 0x47) == (byteArray[1] ^ 0x49))
{
tsc = 0x47;
sc = BitConverter.GetBytes(byteArray[0] ^ 0x47)[0];
}
var lsNewbyte = new List<byte>();
foreach (var item in byteArray)
{
var newByte = BitConverter.GetBytes(item ^ sc);
lsNewbyte.Add(newByte[0]);
}
var newByteArray = lsNewbyte.ToArray();
//FileBinaryConvertHelper.Bytes2File(newByteArray, $@"D:\pp.{keyValuePairs[tsc]}");
FileBinaryConvertHelper.Bytes2File(newByteArray, path+$".convert.{keyValuePairs[tsc]}");
}
}
public class FileBinaryConvertHelper
{
public static byte[] File2Bytes(string path)
{
if (!System.IO.File.Exists(path))
{
return new byte[0];
}
FileInfo fi = new FileInfo(path);
byte[] buff = new byte[fi.Length];
FileStream fs = fi.OpenRead();
fs.Read(buff, 0, Convert.ToInt32(fs.Length));
fs.Close();
return buff;
}
public static void Bytes2File(byte[] buff, string savepath)
{
if (System.IO.File.Exists(savepath))
{
System.IO.File.Delete(savepath);
}
FileStream fs = new FileStream(savepath, FileMode.CreateNew);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff, 0, buff.Length);
bw.Close();
fs.Close();
}
}
}