DiscUtils
DiscUtils copied to clipboard
How to record the content of a file .img ext4
How to record the content of a file I read that file from an img file => convert it into hex => I want to reload that hex back into the previous file but keep getting the error Only existing files can be opened
code me (function WriteHexToFileFromImage)
public static string ReadFileBinaryAsHexFromImage(string imagePath, string filePathInImage)
{
string hexContent = "";
try
{
using (Stream fs = new FileStream(imagePath, FileMode.Open))
{
using (DiscFileSystem fileSystem = new ExtFileSystem(fs))
{
using (Stream fileStream = fileSystem.OpenFile(filePathInImage, FileMode.Open))
{
byte[] fileBytes = new byte[fileStream.Length];
fileStream.Read(fileBytes, 0, fileBytes.Length);
StringBuilder sb = new StringBuilder();
foreach (byte b in fileBytes)
{
sb.AppendFormat("{0:X2} ", b);
}
hexContent = sb.ToString().Trim();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error => ReadFileBinaryAsHexFromImage\n{ex.Message}");
MessageBox.Show($"Error => ReadFileBinaryAsHexFromImage\n=>{ex.Message}");
}
return hexContent;
}
public static void WriteHexToFileFromImage(string hexContent, string imagePath, string filePathInImage)
{
try
{
using (Stream fs = new FileStream(imagePath, FileMode.OpenOrCreate))
{
using (DiscFileSystem fileSystem = new ExtFileSystem(fs))
{
using (Stream fileStream = fileSystem.OpenFile(filePathInImage, FileMode.OpenOrCreate))
{
hexContent = hexContent.Replace(" ", "");
byte[] fileBytes = new byte[hexContent.Length / 2];
for (int i = 0; i < fileBytes.Length; i++)
{
fileBytes[i] = Convert.ToByte(hexContent.Substring(i * 2, 2), 16);
}
fileStream.SetLength(0);
fileStream.Write(fileBytes, 0, fileBytes.Length); // Ghi dữ liệu mới
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error => WriteHexToFileFromImage\n{ex.Message}");
MessageBox.Show($"Error => WriteHexToFileFromImage\n{ex.Message}");
}
}
This library only supports reading ext file systems, not modifying. However, since you can get information about where a file is stored, you could update this location directly in the image, provided you do not need to change the file size or similar.