I have an image in ushort variable, want to save this image in binary format.
Please, anyone, tell me How can this be done using C#?
I have tried this but its not working
ushort[] Depthdata;
Depthdata = new ushort[DWidth * DHeight];
string s1 = string.Format("{0}", count_depth);
FileStream fs = new FileStream("C:\\img" + s1 + ".bin", FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
string image_str = Convert.ToString(Imagedata);
bw.Write(image_str);
bw.Close();
fs.Close();
Here is attached my full code
I would like to mention that the code here, and the one in your link are different...
In any case, going by the one in your link:
ushort[] Depthdata;
....
string s1 = string.Format("{0}", count_depth);
FileStream fs = new FileStream("G:\\test" + s1 + ".bin", FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
string depth_str = Convert.ToString(Depthdata);
bw.Write(depth_str);
bw.Close();
fs.Close();
You shouldn't actually need to convert your Depthdata to a string. BinaryWriter can actually take a ushort value in one of its overloads. Why not just iterate through and write it out? Also, you should use using statements for your filestream and binarywriter.
Try the following:
using(FileStream fs = new FileStream("G:\\test" + s1 + ".bin", FileMode.Create, FileAccess.Write))
{
using(BinaryWriter bw = new BinaryWriter(fs))
{
foreach(ushort value in Depthdata)
{
bw.write(value);
}
}
}
I think this will help you.i tested this on *.tiff file
first make separate Class Ext
public static class Ext
{
public static string ToHexString(this byte[] hex)
{
if (hex == null) return null;
if (hex.Length == 0) return string.Empty;
var s = new StringBuilder();
foreach (byte b in hex)
{
s.Append(b.ToString("x2"));
}
return s.ToString().ToUpper();
}
}
then you can Add following code to convert image to string binary
FileStream fs=new FileStream(ImgPathID, FileMode.Open, FileAccess.Read); //set file stream
Byte[] bindata=new byte[Convert.ToInt32(fs.Length)];
fs.Read(bindata, 0, Convert.ToInt32(fs.Length));
string bindatastring = Ext.ToHexString(bindata);// call to class
Related
Can anyone explain me about the following code what it is doing and
why it is substracting the size by 44.
public byte[] recorded_file = new byte[1000000];
public bool recorded_first_stream;
public int recorded_file_location;
public async void TestFile(object object_name)
{
string file_name = (string)object_name;
string full_file_name = System.IO.Path.Combine
(Properties.Settings.Default.wave_files_location, file_name);
if (File.Exists(full_file_name))
{
// WaveStream fileStream = new AudioFileReader(full_file_name);
recorded_first_stream = true;
FileStream fs = File.Open(full_file_name, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite);
recorded_file_location = (int)new System.IO.FileInfo(full_file_name).Length - 44;
BinaryReader wave_file = new BinaryReader(fs);
wave_file.BaseStream.Seek(44, SeekOrigin.Begin);
byte[] wave_bytes = wave_file.ReadBytes(1000000);
Buffer.BlockCopy(wave_bytes, 0, recorded_file, 0, wave_bytes.Length);
}
I need to create a StreamWriter from a FileStream object and append some text to
the file. It is assumed that the FileStream object that is being used has been created with FileMode.OpenOrCreate and FileAccess.ReadWrite. I have:
using (FileStream fs = GetCurrentFileStream())
{
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("StringToAppend");
sw.Flush();
}
However this just overwrites the file from the beginning. How do I move to the end of the file? Is there perhaps a way to change the FileMode to Append and FileAccess to Write after the FileStream has been created?
Edit: As mentioned above I need to do this using a FileStream object. The answers from Open existing file, append a single line assume that I can create a new StreamWriter from the file path which I don't have.
Edit 2: Added truncated version of GetCurrentFileStream().
public static FileStream GetCurrentFileStream()
{
String fileName = getFileName();
FileStream fs = OpenFileWhenAvailable(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
}
public static FileStream OpenFileWhenAvailable(String fileName, FileMode fileMode, FileAccess fileAccess, FileShare fileShare)
{
int tries = 0;
int timeout = 10 * 1000;
while (true)
{
tries++;
try
{
return new FileStream(fileName, fileMode, fileAccess, fileShare);
}
catch (IOException ex)
{
if (tries * 100 > timeout)
{
return null;
}
else
{
System.Threading.Thread.Sleep(100);
}
}
}
}
GetCurrentFileStream is used in several different contexts, so changing the FileMode and FileAccess directly is not an option. I do not wish to make a separate version of GetCurrentFileStream just for this one case, which is why I'm asking if there is a way to jump to the end of the stream and append a string when the FileStream object has already been created.
If I understood correctly, you want to append your line to a created file:
using (FileStream fs = GetCurrentFileStream())
{
StreamWriter sw = new StreamWriter(fs, true);
sw.WriteLine("StringToAppend");
sw.Flush();
}
With this overload of the StreamWriter constructor you choose if you append the file, or overwrite it.
It will be really cool if you show your implementation of method GetCurrentStream():
using (FileStream fileStream = new FileStream(fileName,FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(something);
}
Update:
using (FileStream fs = GetCurrentFileStream())
{
StreamWriter sw = new StreamWriter(fs);
long endPoint=fs.Length;
// Set the stream position to the end of the file.
fs.Seek(endPoint, SeekOrigin.Begin);
sw.WriteLine("StringToAppend");
sw.Flush();
}
If you really really wanted to, you could pretty this up....
static int iMaxLogLength = 15000;
static int iTrimmedLogLength = -2000;
static public void writeToFile2(string strMessage, string strLogFileDirectory, int iLogLevel)
{
string strFile = strLogFileDirectory + "log.log";
try
{
FileInfo fi = new FileInfo(strFile);
Byte[] bytesRead = null;
if (fi.Length > iMaxLogLength)
{
using (BinaryReader br = new BinaryReader(File.Open(strFile, FileMode.Open)))
{
// Go to the end of the file and backup some
br.BaseStream.Seek(iTrimmedLogLength, SeekOrigin.End);
// Read that.
bytesRead = br.ReadBytes((-1 * iTrimmedLogLength));
}
}
byte[] newLine = System.Text.ASCIIEncoding.ASCII.GetBytes(Environment.NewLine);
FileStream fs = null;
if (fi.Length < iMaxLogLength)
fs = new FileStream(strFile, FileMode.Append, FileAccess.Write, FileShare.Read);
else
fs = new FileStream(strFile, FileMode.Create, FileAccess.Write, FileShare.Read);
using (fs)
{
if (bytesRead != null)
{
fs.Write(bytesRead, 0, bytesRead.Length);
fs.Write(newLine, 0, newLine.Length);
Byte[] lineBreak = Encoding.ASCII.GetBytes("### " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " *** *** *** New Log Start Position *** *** *** *** ###");
fs.Write(lineBreak, 0, lineBreak.Length);
fs.Write(newLine, 0, newLine.Length);
}
Byte[] sendBytes = Encoding.ASCII.GetBytes(strMessage);
fs.Write(sendBytes, 0, sendBytes.Length);
fs.Write(newLine, 0, newLine.Length);
}
}
catch (Exception ex)
{
; // Write to event or something
}
}
I would like to decompress in C# some DeflateCoded data (PDF extracted).
Unfortunately I got every time the exception "Found invalid data while decoding.".
But the data are valid.
private void Decompress()
{
FileStream fs = new FileStream(#"S:\Temp\myFile.bin", FileMode.Open);
//First two bytes are irrelevant
fs.ReadByte();
fs.ReadByte();
DeflateStream d_Stream = new DeflateStream(fs, CompressionMode.Decompress);
StreamToFile(d_Stream, #"S:\Temp\myFile1.txt", FileMode.OpenOrCreate);
d_Stream.Close();
fs.Close();
}
private static void StreamToFile(Stream inputStream, string outputFile, FileMode fileMode)
{
if (inputStream == null)
throw new ArgumentNullException("inputStream");
if (String.IsNullOrEmpty(outputFile))
throw new ArgumentException("Argument null or empty.", "outputFile");
using (FileStream outputStream = new FileStream(outputFile, fileMode, FileAccess.Write))
{
int cnt = 0;
const int LEN = 4096;
byte[] buffer = new byte[LEN];
while ((cnt = inputStream.Read(buffer, 0, LEN)) != 0)
outputStream.Write(buffer, 0, cnt);
}
}
Does anyone has some ideas?
Thanks.
I added this for test data:-
private static void Compress()
{
FileStream fs = new FileStream(#"C:\Temp\myFile.bin", FileMode.Create);
DeflateStream d_Stream = new DeflateStream(fs, CompressionMode.Compress);
for (byte n = 0; n < 255; n++)
d_Stream.WriteByte(n);
d_Stream.Close();
fs.Close();
}
Modified Decompress like this:-
private static void Decompress()
{
FileStream fs = new FileStream(#"C:\Temp\myFile.bin", FileMode.Open);
//First two bytes are irrelevant
// fs.ReadByte();
// fs.ReadByte();
DeflateStream d_Stream = new DeflateStream(fs, CompressionMode.Decompress);
StreamToFile(d_Stream, #"C:\Temp\myFile1.txt", FileMode.OpenOrCreate);
d_Stream.Close();
fs.Close();
}
Ran it like this:-
static void Main(string[] args)
{
Compress();
Decompress();
}
And got no errors.
I conclude that either the first two bytes are relevant (Obviously they are with my particular test data.) or
that your data has a problem.
Can we have some of your test data to play with?
(Obviously don't if it's sensitive)
private static string decompress(byte[] input)
{
byte[] cutinput = new byte[input.Length - 2];
Array.Copy(input, 2, cutinput, 0, cutinput.Length);
var stream = new MemoryStream();
using (var compressStream = new MemoryStream(cutinput))
using (var decompressor = new DeflateStream(compressStream, CompressionMode.Decompress))
decompressor.CopyTo(stream);
return Encoding.Default.GetString(stream.ToArray());
}
Thank you user159335 and user1011394 for bringing me on the right track! Just pass all bytes of the stream to input of above function. Make sure the bytecount is the same as the length specified.
All you need to do is use GZip instead of Deflate. Below is the code I use for the content of the stream… endstream section in a PDF document:
using System.IO.Compression;
public void DecompressStreamData(byte[] data)
{
int start = 0;
while ((this.data[start] == 0x0a) | (this.data[start] == 0x0d)) start++; // skip trailling cr, lf
byte[] tempdata = new byte[this.data.Length - start];
Array.Copy(data, start, tempdata, 0, data.Length - start);
MemoryStream msInput = new MemoryStream(tempdata);
MemoryStream msOutput = new MemoryStream();
try
{
GZipStream decomp = new GZipStream(msInput, CompressionMode.Decompress);
decomp.CopyTo(msOutput);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
None of the solutions worked for me on Deflate attachments in a PDF/A-3 document. Some research showed that .NET DeflateStream does not support compressed streams with a header and trailer as per RFC1950.
Error message for reference: The archive entry was compressed using an unsupported compression method.
The solution is to use an alternative library SharpZipLib
Here is a simple method that successfully decoded a Deflate attachment from a PDF/A-3 file for me:
public static string SZLDecompress(byte[] data) {
var outputStream = new MemoryStream();
using var compressedStream = new MemoryStream(data);
using var inputStream = new InflaterInputStream(compressedStream);
inputStream.CopyTo(outputStream);
outputStream.Position = 0;
return Encoding.Default.GetString(outputStream.ToArray());
}
I need to temporary store a file upload to a MemoryStream.
What would be the best method to do this using asp.net (3.5)?
Here's what I have so far. It works (locally tested), but it does not look right to me.
protected void lnkUploadFile_Click(object sender, EventArgs e)
{
MemoryStream memStream = new MemoryStream();
BinaryWriter sWriter = new BinaryWriter(memStream);
foreach (byte b in flUpload.FileBytes)
{
sWriter.Write(b);
}
sWriter.Flush();
// writing to file to verify file stream converted correctly
FileStream fstream = new FileStream(#"C:/test/" + flUpload.FileName, FileMode.Create);
memStream.WriteTo(fstream);
fstream.Dispose();
memStream.Dispose();
}
If flUpload.FileBytes is a byte array, you can use the MemoryStream constructor that accepts the contained data as a parameter:
MemoryStream memStream = new MemoryStream(flUpload.FileBytes);
If not (if it just implements IEnumerable), you can convert it to a byte array using Linq:
MemoryStream memStream = new MemoryStream(flUpload.FileBytes.ToArray());
protected void lnkUploadFile_Click(object sender, EventArgs e)
{
using (MemoryStream memStream = new MemoryStream(flUpload.FileBytes))
{
using (FileStream fstream = new FileStream(#"C:/test/" +
flUpload.FileName, FileMode.Create))
{
memStream.WriteTo(fstream);
}
}
}
Might be easier to work with as a string... all depends on what you're going to do with it I guess.
System.IO.StreamReader reader = new System.IO.StreamReader("path");
string file = reader.ReadToEnd();
Or if you need the bytes there is actually a code snipet "filReadBin" you can use that produces this:
byte[] fileContents;
fileContents = System.IO.File.ReadAllBytes(#"C:\Test.txt");
Just three lines.
if (flUpload.FileName.Length > 0)
{
string directoryPath="C:\\SomeFolderName";
flUpload.SaveAs(directoryPath + "\\" + fileUpload.FileName);
}
I have the below methods:
public static byte[] ConvertFileToBytes(string filePath)
{
var fInfo = new FileInfo(filePath);
var numBytes = fInfo.Length;
var dLen = Convert.ToDouble(fInfo.Length / 1000000);
var fStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var br = new BinaryReader(fStream);
var data = br.ReadBytes((int)numBytes);
br.Close();
fStream.Close();
fStream.Dispose();
return data;
}
public static void ConvertBytesToFile(byte[] file, string filePath)
{
var ms = new MemoryStream(file);
var fs = new FileStream(filePath, FileMode.Create);
ms.WriteTo(fs);
ms.Close();
fs.Close();
fs.Dispose();
}
What is the correct to name these methods? (because ConvertXXXtoYYY just doesn't cut it in a Utilities library)
How about File.ReadAllBytes and File.WriteAllBytes ;)
The terms usually used are "serialize" and "deserialize" (or sometimes "marshal" and "demarshal").
Marshalling/Unmarshalling might be the appropriate term.
http://en.wikipedia.org/wiki/Marshalling_(computer_science)
In C++ they would be called read and write.
The WriteAllBytes and ReadAllBytes are a good suggestion, but to answer your Question ...
Save() would be a good choice for renaming of ConvertToFile() and Object.CreateFromFile() for the reverse.