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();
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 want to read data from exe file.
On java i read exe perfect from start to end,
bun on c# i cannot read all file.
File lenth is true but in result show only head of exe file
string fileLoc = filePaths[0];
FileStream fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
foreach(byte b in bin){
Console.Write((char)b);
}
fs.Close();
output is only the head of exe: MZP
Cannot reproduce:
string fileLoc = //my path to git.exe
FileStream fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
foreach (byte b in bin)
{
Console.Write((char)b);
}
fs.Close()
It writes all data from it.
But i see many problems in your code:
1) never do work with files with such unsafer way (if error occured file will not close) rewrite:
string fileLoc = //my path to git.exe
using(FileStream fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read)) {
BinaryReader br = new BinaryReader(fs);
byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
foreach (byte b in bin)
{
Console.Write((char)b);
}
} // no more explicit close required, but it will closed with guarantee
2) not mistake but in C# it's preferable use var (analoug to auto in c++)
using(var fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read)) {
var br = new BinaryReader(fs);
var bin = br.ReadBytes(Convert.ToInt32(fs.Length));
foreach (var b in bin)
{
Console.Write((char)b);
}
} //it still strong typed, but type referenced only once at right side of assigment
3) Not require use Convert for explicitly castable types (long->int)
var bin = br.ReadBytes((int)fs.Length);
4) I don't know why only MZP is written in your case, but can imagine that if you cast byte to char you will get many not-printable symbols including \r \n \f and so on in output - how your concrete terminal will be react? - i don't know
5) If you print (char)b just for test of bin - why so badly - why you not simply test bin.Length or why you print (char)b and not b+" " ? Otherwise if you really want to print bytes to console - it's bad idea anyway - look (4)
6) Why BinaryReader? if you just want read all
using(var fs = new FileStream(fileLoc, FileMode.Open, FileAccess.Read, FileShare.Read)) {
var bin = new byte[(int)fs.Length];
// u can use usual stream pattern
int l=0; while((l+=fs.Read(bin,t,bin.Length-t))<bin.Length);
foreach (var b in bin)
{
Console.Write((char)b);
}
}
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
In the following code I get the error "stream was not writable":
class Class1
{
private static void Main()
{
FileStream fs = new FileStream("C:\\fFile.txt",
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.ReadWrite);
StreamReader r = new StreamReader(fs);
string t = r.ReadLine();
r.Close();
Console.WriteLine(t);
StreamWriter w = new StreamWriter(fs);
w.WriteLine("string");
w.Flush();
w.Close();
fs.Close();
}
}
The error occurs at this line StreamWriter w = new StreamWriter(fs);
Why is this?
from msdn
Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.
So the stream you try to write to is invalid you need to reopen the stream and reopen the file.
r.Close();
There's your problem after you read. The close() methods close the underlying stream.
You'll have to re-open the file since the read closes it:
FileStream fs = new FileStream("C:\\test.txt",
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.ReadWrite);
using (StreamReader r = new StreamReader(fs))
{
string t = r.ReadLine();
r.Close();
Console.WriteLine(t);
}
fs = new FileStream("C:\\test.txt",
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.ReadWrite);
using (StreamWriter w = new StreamWriter(fs))
{
w.WriteLine("string");
w.Flush();
w.Close();
}
fs.Close();
Dont close the first StreamWriter, it will close the underlying stream.
And use using statements as Oscar suggests.
using (FileStream fs = new FileStream("C:\\temp\\fFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
StreamReader r = new StreamReader(fs);
string t = r.ReadLine();
Console.WriteLine(t);
StreamWriter w = new StreamWriter(fs);
w.WriteLine("string");
w.Close();
r.Close();
fs.Close();
}
Do not close the StreamReader. Just comment the line below and it will work.
r.Close();
I am trying to read from the isolated storage if the file is exist it will delete the whole file and directories before recreating the file.
Then if the file does not exist it will create the file and directories.
Below is my code: I got a error of opertion not permitted on isolated storage at write file
int indexQues;
string rate;
string[] queSplit;
string[] rateSplit;
private void saveBtn_Click(object sender, RoutedEventArgs e)
{
indexQues = queListPicker.SelectedIndex;
rate = rateListPicker.SelectedItem.ToString();
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
try
{
//For question
StreamReader readFileQue = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Open, myStore));
//For passing rate
StreamReader readFileRate = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Open, myStore));
String queText = readFileQue.ReadLine();
queSplit = queText.Split(new char[] { '^' });
String rateText = readFileRate.ReadLine();
rateSplit = rateText.Split(new char[] { '^' });
readFileQue.Close();
readFileRate.Close();
int noOfQueInDB = queSplit.Count();
int noOfRateInDB = rateSplit.Count();
MessageBox.Show(noOfQueInDB.ToString());
//if (noOfQueInDB == 2)
//{
myStore.DeleteFile("SettingFolder\\queSetting.txt");
myStore.DeleteFile("SettingFolder\\rateSetting.txt");
myStore.DeleteDirectory("SettingFolder");
MessageBox.Show("Deleted all");
myStore.CreateDirectory("SettingFolder");
//Retrieve the content of "noOfQues"
//And write it into queSetting.txt
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Create, myStore));
writeFile.Write(indexQues);
// writeFile.Write("^" + indexQues);
writeFile.Close();
StreamWriter writeFile1 = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\rateSetting.txt", FileMode.Create, myStore));
writeFile1.Write(rate);
writeFile1.Close();
MessageBox.Show("Setting Saved");
MessageBox.Show(indexQues.ToString());
MessageBox.Show(rate);
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
//}
}
catch (Exception)
{
myStore.CreateDirectory("SettingFolder");
//Retrieve the content of "noOfQues"
//And write it into queSetting.txt
// ****
// **** The following line throws an exception
// ****
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Create, myStore));
writeFile.Write(indexQues);
// writeFile.Write("^" + indexQues);
writeFile.Close();
StreamWriter writeFile1 = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\rateSetting.txt", FileMode.Create, myStore));
writeFile1.Write(rate);
writeFile1.Close();
MessageBox.Show("Setting Saved");
MessageBox.Show(indexQues.ToString());
MessageBox.Show(rate);
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
}
one point - this seems wrong (you open the same file twice ?):
//For question
StreamReader readFileQue = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Open, myStore));
//For passing rate
StreamReader readFileRate = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Open, myStore));
second point - you should use Dispose:
readFileQue.Close(); readFileQue.Dispose(); readFileQue = null;
readFileRate.Close(); readFileRate.Dispose(); readFileRate = null;
third point - user proper FileAccess when creating the files:
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\rateSetting.txt",
FileMode.Create,
FileAccess.Write,
FileShare.Write,
myStore);
Hope the above helps... if not check whether the Directory is really created...
EDIT:
Are you sure the Exception is thrown from the catch-block ? IF so, then there must have happened some Exception before that - what was that Exception?