c# BinaryReader still open after .close(); - c#

I'm making a program that reads file after I select a file and write file in hex. Problem is BinaryReader still open after .Close(); and it gives me System.IO.IOException: the process cannot access the file error when i try to write a file. I'm missing something?
Here is the code that read the file after i select file from dialogbox..
BinaryReader br = new BinaryReader(File.OpenRead(sfile.FileName));
string pted = null;
br.BaseStream.Position = 0x12;
pted += br.ReadByte().ToString("X2");
if (pted == "01")
{
}
else
{
}
br.Close();
And here is the code that writes file when you click a button
Stream st = File.Open(pathTextBox.Text, FileMode.Open);
st.Seek(0x12, SeekOrigin.Begin);
st.WriteByte(0x00);
st.Close();

add br.close in a try catch statement and dispose the binary reader after closing
for example:
try{
br.close();
br.dispose();
}
catch(Exception exp)
{
//Assuming you have included using 'namespace System.Diagnostics'
Debug.WriteLine(exp.ToString());
}
You can read more on BinaryReader here

First check if file is here, then try it with using directive.

As mentioned by Orgen:
if(File.Exists(#pathTextBox.Text)
{
using(Stream st = File.Open(pathTextBox.Text, FileMode.Open))
{
st.Seek(0x12, SeekOrigin.Begin);
st.WriteByte(0x00);
}
}
the using() will take care of the disposable.

Related

Odd file does not exist error

I'm running into an error that I can't catch and it should not be there.
if (System.IO.File.Exists (PathToMyFile))
{
try{
FileStream fs = new FileStream(PathToMyFile, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
myFile =Convert.ToBase64String (bytes) ;
}
catch{}
}
For some reason , sometimes I get a exception error that the file does not exist when It most definitely is there. The very first "If statement" even says it is there yet when trying to open the file I sometimes get a massive app crash that the catch does not "catch" .
Like I said, it's a random error, most of the time the code is perfect but the odd occasion seems to throw an error that the app stops working .
First thing is to make sure you close the file\stream
So you can call fs.Close() or using
if (File.Exists(pathToMyFile))
{
try
{
using (var fs = new FileStream(pathToMyFile, FileMode.Open, FileAccess.Read))
{
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32) fs.Length);
br.Close();
fs.Close();
myFile = Convert.ToBase64String(bytes);
}
}
catch
{
// Log exception
}
}
Second, if you need to read the file as string, simply use
if (File.Exists(pathToMyFile))
{
try
{
myFile = File.ReadAllText(pathToMyFile);
}
catch
{
// Log exception
}
}

I cant copy files using FileStream

I am trying to read/write files using FileStream. Code is working but After copied files all I get an empty file. String data inside the file is not copied.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if(saveFileDialog1.ShowDialog()==DialogResult.OK)
{
FileStream streamR = new FileStream(openFileDialog1.FileName, FileMode.Open);
byte[] buffer = new byte[streamR.Length];
streamR.Read(buffer, 0, buffer.Length);
FileStream streamW = new FileStream(saveFileDialog1.FileName,FileMode.Create);
int read_byte = 0;
while ((read_byte = streamR.Read(buffer, 0, buffer.Length)) > 0)
{
streamW.Write(buffer, 0, read_byte);
}
}
}
When using streams, you should use the 'using' command:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if(saveFileDialog1.ShowDialog()==DialogResult.OK)
{
using (FileStream streamR = new FileStream(openFileDialog1.FileName, FileMode.Open))
{
using (FileStream streamW = new FileStream(saveFileDialog1.FileName,FileMode.Create))
{
byte[] buffer = new byte[streamR.Length];
int read_byte = 0;
while ((read_byte = streamR.Read(buffer, 0, buffer.Length)) > 0)
{
streamW.Write(buffer, 0, read_byte);
}
}
}
}
}
It will automatically flush, close and dispose the streams for you.
What actually stops your code from working, is the flush() and close() command.
However, it's still recommended to use the 'using' command.
A second way is to wrap everything in a try finally block and dispose the stream in the finally block:
using statement FileStream and / or StreamReader - Visual Studio 2012 Warnings
Anyway, I would suggest reading some more information about streams before continuing.
On the other hand ... if it's just for copying files, it would be simpler to use the Fil.Copy method.
Edit: Also ... loading the original file completely into a byte-array can cause some extra problems when your file is quite large.
The buffer is there to read chunks from the original file and process them.
I just corrected your code to make it work ... but it's far from perfect.
I would do something along these lines:
if (openFileDialog1.ShowDialog() == DialogResult.OK
&& saveFileDialog1.ShowDialog() == DialogResult.OK){
try {
if (File.Exists(saveFileDialog1.FileName)) {
File.Delete(saveFileDialog1.FileName);
}
File.Copy(openFileDialog1.FileName, saveFileDialog1.FileName);
} catch (Exception e){
//handle or throw e
}
}

BinaryWriter in loop causes "file is being used by another process" error even though it is closed and 'using'

Title sais it all really.
private bool addToBinary(byte[] msg, string filepath)
{
bool succ = false;
do
{
try
{
using (Stream fileStream = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.None))
{
using (BinaryWriter bw = new BinaryWriter(fileStream))
{
bw.Write(msg);
bw.Flush();
fileStream.Flush();
bw.Close();
}
}
succ = true;
}
catch (IOException ex) { Console.WriteLine("Write Exception (addToBinary) : " + ex.Message); }
catch (Exception ex) { Console.WriteLine("Some Exception occured (addToBinary) : " + ex.Message); return false; }
} while (!succ);
return true;
}
(bw.close also closes the underlying stream)
Using this in any loop causes an output such as;
A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll
Write Exception (addToBinary) : The process cannot access the file 'C:\test\test.png' because it is being used by another process.
The bigger the file gets, the more of these errors pop up. It does get through eventually but it significantly reduces file writing speed. It's the Stream fileStream = bit that causes the exception.
What did I do wrong?
Example usage;
do
{
serverStream = clientSocket.GetStream();
bytesRead = serverStream.Read(inStream, 0, buffSize); //How many bytes did we just read from the stream?
recstrbytes = new byte[bytesRead]; //Final byte array
Array.Copy(inStream, recstrbytes, bytesRead); //Copy from inStream to the final byte array
addToBinary(recstrbytes, #"C:\test\test.png"); //Append final byte array to binary
received += recstrbytes.Length; //Increment bytes received
}while (received < filesize);
You need to first check if you can access the file before using Stream to read the file.
You can have a look at this link :
Best way to handle errors when opening file
Have a look at the answers
Although I posted my answer
https://stackoverflow.com/a/9503939/448407 but you can look at the post marked as answer.
Only read the file contents if you can access the file and I think it will then work.
Some good advice style wise for those stacked using statements. When you start using more than one it is often neater to use the following style:
using (Stream fileStream = new FileStream(filepath, FileMode.Append, FileAccess.Write, FileShare.None))
using (BinaryWriter bw = new BinaryWriter(fileStream))
{
bw.Write(msg);
bw.Flush();
fileStream.Flush();
bw.Close();
}
I'm afraid I can't solve your question though, but I'm not sure how much of a good an idea it is to repeatedly try and write to the stream if it isn't successful the first time round.

C# close stream and delete file if something failed

I'm working with a file stream in C#. It's a storage cache, so if something goes bad writing the file (corrupted data, ...), I need to delete the file and rethrow the exception to report the problem. I'm thinking on how to implement it in the best way. My first attempt was:
Stream fileStream = null;
try
{
fileStream = new FileStream(GetStorageFile(),
FileMode.Create, FileAccess.Write, FileShare.Write);
//write the file ...
}
catch (Exception ex)
{
//Close the stream first
if (fileStream != null)
{
fileStream.Close();
}
//Delete the file
File.Delete(GetStorageFile());
//Re-throw exception
throw;
}
finally
{
//Close stream for the normal case
if (fileStream != null)
{
fileStream.Close();
}
}
As you will see, if something goes bad writing the file, the fileStream will be closed twice. I know that it works, but I don't think that is the best implementation.
I think that I could remove the finally block, and close the stream in the try block, but I have posted this here because you guys are experts and I want to hear the voice of an expert.
If you put the fileStream in a using block you don't need to worry about closing it, and then just leave the cleaning up (deleting of the file in the catch block.
try
{
using (FileStream fileStream = new FileStream(GetStorageFile(),
FileMode.Create, FileAccess.Write, FileShare.Write))
{
//write the file ...
}
}
catch (Exception ex)
{
File.Delete(GetStorageFile());
//Re-throw exception
throw;
}
I believe what you want is this:
var fs = new FileStream(result.FilePath, FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose);
I've used it with ASP.Net to have the web server return a result to a temp file that's on disk, but to make sure it's cleaned up after the web server finishes serving it to the client.
public static IActionResult TempFile(string tempPath, string mimeType, string fileDownloadName)
{
var fs = new FileStream(tempPath, FileMode.Open, FileAccess.Read, FileShare.None, 4096, FileOptions.DeleteOnClose);
var actionResult = new FileStreamResult(fileStream: fs, contentType: mimeType)
{
FileDownloadName = fileDownloadName
};
return actionResult;
}

GZipStream zip file invalid or corrupted

I have a problem when opening a zip file. I am using this code to zip the file:
public static string Zip_File(string soruce , string target)
{
try
{
byte[] bufferWrite;
using (FileStream fsSource = new FileStream(soruce, FileMode.Open, FileAccess.Read, FileShare.Read))
{
bufferWrite = new byte[fsSource.Length];
fsSource.Read(bufferWrite, 0, bufferWrite.Length);
using (FileStream fsDest = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write))
{
using (GZipStream gzCompressed = new GZipStream(fsDest, CompressionMode.Compress, true))
{
gzCompressed.Write(bufferWrite, 0, bufferWrite.Length);
bufferWrite = null;
fsSource.Close();
gzCompressed.Close();
fsDest.Close();
}
}
}
return "success";
}
catch (Exception ex)
{
return ex.Message;
}
}
When I call this function, I am receiving "success" message, but I can't open the zip file. This is my function call code:
ZipFiles.Zip_File(#"C:\Documents and Settings\ccspl\Desktop\IntegrityDVR.mdb", #"C:\Documents and Settings\ccspl\Desktop\a.zip")
This is the error message I receive:
the compressed(folder) is invalid or corrupted
GZipStream does not create .zip files. It creates .gz files. If you need to create .zip files, you should use something like SharpZipLib.
but, wait a minute, GZipStream doesn't create zip file, it creates gzip files as I know, Zipping files using GZipStream should help
Why not use SharpZipLib? It makes this a lot easier.
sample code for DotNetZip, an open source zip library.
public static string ZipFile(String source, String target)
{
try
{
using (ZipFile zip = new ZipFile()
{
zip.AddFile(source);
zip.Save(target);
}
return "success";
}
catch {}
return "failure";
}

Categories