I am writing the integer value in binary file as follows:-
int val =10;
FileStream fs = new FileStream("BinaryFile.bin", FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs, Encoding.Unicode);
bw.Write(val);
//Reading value from binary as:-
FileStream fs = new FileStream("BinaryFile.bin", FileMode.Open);
BinaryReader br = new BinaryReader(fs, Encoding.Unicode);
int x = br.ReadInt32();
Value retrieved is: 1.092616E + 09
I am getting this value instead of '10'
Is there any other method to retrieve the int value?
Try by making change in BinaryWriter constructor
as
FileStream fs = new FileStream("iram.bin", FileMode.Create);
// Create the writer for data.
BinaryWriter w = new BinaryWriter(fs);
w.Write((int) 2000);
w.Close();
fs.Close();
and read using
using (FileStream fs2 = new FileStream("iram.bin", FileMode.Open))
{
using(BinaryReader r = new BinaryReader(fs2))
{
var integerValue = r.ReadInt32();
}
}
More detail Writing to .bin binary file
Related
I want to read a binary file line by line (I'm writing of course continously, but I know that after 457 bytes new data start and I know exactly the byte structure and where which information is written to) and change a special entry of the line. I get an System.IO.IOException when I try to access the same file with both BinaryReader and BinaryWriter. I use locking to prevent that the file is accessed from somewhere else.
My code is:
using (FileStream fs2 = new FileStream(testfile, FileMode.Open, FileAccess.Read))
{
using (BinaryReader r = new BinaryReader(fs2))
{
using (BinaryWriter bw = new BinaryWriter(new FileStream(testfile, FileMode.Open, FileAccess.Write), utf8))
{
for (int i = 0; i < 11000; i+=457)
{
int myint = r.ReadInt64();
bw.Seek(i, SeekOrigin.Current);
bw.Write(myint*2);
}
}
}
}
How can I do this?
Do not create the second FileStream because the file is locked for the read operation by the first FileStream object.
If you are sure about file structure, the exception only can come out from 2nd FileStream instantiation. See link below for more information:
Read and Write to File at the same time
It is working for me using the following code:
if (File.Exists(testfile))
{
FileInfo fi = new FileInfo(testfile);
using (FileStream fs2 = new FileStream(testfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (BinaryReader r = new BinaryReader(fs2))
{
r.BaseStream.Seek(0, SeekOrigin.Begin);
using (BinaryWriter bw = new BinaryWriter(new FileStream(testfile, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)))
{
for (int i = 0; i <= (fi.Length-177); i += 177)//181
{
}
}
}
}
}
I encrypted a pdf and would like to save it to the database, below are the codes as to how I did it. I would like to know if there are any ways to set the Created "PDFEncrypted.pdf" onto the Stream fs without using a FileUploader?
string WorkingFolder = Server.MapPath("~/Files/");
string InputFile = Path.Combine(WorkingFolder, "PDF.pdf");
string OutputFile = Path.Combine(WorkingFolder, "PDFEncrypted.pdf");
using (Stream input = new FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader reader = new PdfReader(InputFile);
PdfEncryptor.Encrypt(reader, output, true, "pass123", "secret", PdfWriter.ALLOW_SCREENREADERS);
}
}
So I have these codes to upload it
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
How can I create a .csv file implicitly/automatically by using the correct method, add text to that file existing in memory and then convert to in memory data to a byte array?
string path = #"C:\test.txt";
File.WriteAllLines(path, GetLines());
byte[] bytes = System.IO.File.ReadAllBytes(path);
With that approach I create a file always (good), write into it (good) then close it (bad) then open the file again from a path and read it from the hard disc (bad)
How can I improve that?
UPDATE
One nearly good approach would be:
using (var fs = new FileStream(#"C:\test.csv", FileMode.Create, FileAccess.ReadWrite))
{
using (var memoryStream = new MemoryStream())
{
fs.CopyTo(memoryStream );
return memoryStream .ToArray();
}
}
but I am not able to write text into that filestream... just bytes...
UPDATE 2
using (var fs = File.Create(#"C:\temp\test.csv"))
{
using (var sw = new StreamWriter(fs, Encoding.Default))
{
using (var ms = new MemoryStream())
{
String message = "Message is the correct ääüö Pi(\u03a0), and Sigma (\u03a3).";
sw.Write(message);
sw.Flush();
fs.CopyTo(ms);
return ms.ToArray();
}
}
}
The string message is not persisted to the test.csv file. Anyone knows why?
Write text into Memory Stream.
byte[] bytes = null;
using (var ms = new MemoryStream())
{
using(TextWriter tw = new StreamWriter(ms)){
tw.Write("blabla");
tw.Flush();
ms.Position = 0;
bytes = ms.ToArray();
}
}
UPDATE
Use file stream Directly and write to File
using (var fs = new FileStream(#"C:\ed\test.csv", FileMode.Create, FileAccess.ReadWrite))
{
using (TextWriter tw = new StreamWriter(fs))
{
tw.Write("blabla");
tw.Flush();
}
}
You can get a byte array from a string using encoding:
Encoding.ASCII.GetBytes(aString);
Or
Encoding.UTF8.GetBytes(aString);
But I don't know why you would want a csv as bytes. You could load the entire file to a string, add to it and then save it:
string content;
using (var reader = new StreamReader(filename))
{
content = reader.ReadToEnd();
}
content += "x,y,z";
using (var writer = new StreamWriter(filename))
{
writer.Write(content);
}
Update: Create a csv in memory and pass back as bytes:
var stringBuilder = new StringBuilder();
foreach(var line in GetLines())
{
stringBuilder.AppendLine(line);
}
return Encoding.ASCII.GetBytes(stringBuilder.ToString());
This function doesn't work because another process is using it.
The function must read the file, do something with it's data and write the result to this file.
private void changeToolStripMenuItem_Click(object sender, EventArgs e)
{
LB2.Visible = true;
TB2.Visible = true;
SaveFileDialog save = new SaveFileDialog();
if (save.ShowDialog() == DialogResult.OK)
{
double maxlen;
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
Find(read, out maxlen);
while (read.BaseStream.Position < read.BaseStream.Length)
{
double A = read.ReadDouble();
if (A > 0)
{
read.BaseStream.Seek(-8, SeekOrigin.Current);
w.Write(Find(read, out maxlen));
}
else
w.Write(A);
}
read.BaseStream.Close();
w.BaseStream.Close();
}
}
my psychic debugging sense says that it's the FILE that's in use
And you're getting the error because you didn't close your BinaryReader before you created your BinaryWriter
instead of this
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
...
read.BaseStream.Close();
w.BaseStream.Close();
do this
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
...
read.BaseStream.Close();
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
...
w.BaseStream.Close();
you seem to be opening the same file twice?
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open));
BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create));
Same file. BinaryWriter probably encounters the exception, though I'm not entirely sure because you haven't showed us. You need to close your BinaryReader before you can do anything else with that file.
I would do this to make sure your streams are getting closed
using( BinaryReader read = new BinaryReader(new FileStream(save.FileName, FileMode.Open)))
{
using( BinaryWriter w = new BinaryWriter(new FileStream(save.FileName, FileMode.Create)) )
{
// CODE HERE
}
}
It sounds like you're getting an exception and you're not closing your streams/readers/writers.
Change it to:
var fs=new FileStream(save.FileName, FileMode.OpenOrCreate);
BinaryReader read=new BinaryReader(fs);
BinaryWriter w=new BinaryWriter(fs);
and remove:
w.BaseStream.Close();
Given the code below, why is the decompression not working? "NewFile2.txt" should have the original, decompressed text, but the file is just blank.
ioTests.CompressFile(#"c:\newfile.txt", #"c:\newfile.txt.gz");
ioTests.DecompressFile(#"c:\newfile.txt.gz", #"c:\newfile2.txt");
public void CompressFile(string inFileName, string outFileName)
{
FileStream inFile = new FileStream(inFileName, FileMode.Open);
FileStream outFile = new FileStream(outFileName, FileMode.Create);
GZipStream compStream = new GZipStream(outFile, CompressionMode.Compress);
int theByte = inFile.ReadByte();
while (theByte != -1)
{
compStream.WriteByte((byte)theByte);
theByte = inFile.ReadByte();
}
compStream.Close();
}
public void DecompressFile(string inFileName, string outFileName)
{
FileStream inFile = new FileStream(inFileName, FileMode.Open);
FileStream outFile = new FileStream(outFileName, FileMode.CreateNew);
GZipStream compStream = new GZipStream(inFile, CompressionMode.Decompress);
int theByte = compStream.ReadByte();
while (theByte != -1)
{
outFile.WriteByte((byte)theByte);
theByte = compStream.ReadByte();
}
compStream.Close();
}
outFile.Flush(); // after your loop
I prefer
outFile.Close()
as that flushes the stream and calls the Dispose method, releasing allocated resources.
Since the streams you use implement the IDisposable interface, you should Dispose() / Close() your classes, or use the using statement to do this automatically:
using (FileStream inFile = new FileStream(inFileName, FileMode.Open))
using (FileStream outFile = new FileStream(outFileName, FileMode.Create))
using (GZipStream compStream = new GZipStream(outFile, CompressionMode.Compress)) {
int theByte = inFile.ReadByte();
// ... Rest of your code
}
This roughly translates to:
try {
FileStream inFile = new FileStream(inFileName, FileMode.Open);
FileStream outFile = new FileStream(outFileName, FileMode.Create);
GZipStream compStream = new GZipStream(outFile, CompressionMode.Compress);
int theByte = inFile.ReadByte();
// ... Rest of your code
} finally {
if (inFile != null) inFile.Dispose();
if (outFile != null) outFile.Dispose();
if (compStream != null) compStream.Dispose();
}