How create instance FileStream from FileStream? - c#

How create new instance FileStream without specifying other parameters in the constructor, instead of parameters from source FileStream. How can I do it?
FileStream fs= new FileStream([any parametrs]);
FileStream copy1= new FileStream(parametrs from fs); // First variant
FileStream copy2= new FileStream(fs); // Or second variant
For example, I create fileStream
FileStream fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4 * 1024, true)
Now I want a lot of independent copies from it, but fs doesn't save any parametrs received from constructor.

What's about Stream.CopyTo();
FileStream fs= new FileStream([any parametrs]);
var copy1 = new MemoryStream();
fs.CopyTo(copy1)
It should work

Solved like this
class FileStreamExt : FileStream
{
private string _fileName;
private FileMode _mode;
public FileStreamExt Clone()
{
return new FileStreamExt(_fileName, _mode);
}
public FileStreamExt(string filename, FileMode mode)
: base(filename, mode)
{
_fileName = filename;
_mode = mode;
}
}
FileStreamExt fs = FileStreamExt(_fileName,FileAccess.Read);
FileStreamExt copy = fs.Clone();

Related

Read and write from/to the same line with BinaryReader/BinaryWriter

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
{
}
}
}
}
}

FileStream string method for Read/Write?

I am absolute beginner and I am using VS Community 2017 C# and trying to open file on my android phone (7.0 API 24) and write and read some text in that file. This is my methods that suppose to do that:
public string WriteFile(string fileName, byte content)
{
FileStream fileStream = new FileStream(#fileName,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.None);
fileStream.WriteByte(content);
fileStream.Close();
return "WriteOpen";
}
public string ReadFile(string fileName)
{
FileStream fileStream = new FileStream(#fileName,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.None);
int tekts = fileStream.ReadByte();
fileStream.Close();
return "" + tekts;
}
but I cannot find FileStream method with string arguments, so I use WriteByte and ReadByte just to test writing and reading file.
Any suggestions?

The process cannot access the file because it is being used by another process

public bool ReadFile()
{
string fname = "text.txt";
FileStream fs = null;
fs = new FileStream(fname, FileMode.OpenOrCreate,FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string res = sr.ReadToEnd();
if (res == "1")
return true;
else
return false;
}
public void WriteToFile()
{
string fname = "text.txt";
FileStream fs = null;
fs = new FileStream(fname, FileMode.Open,FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.Write("1");
}
So it should work like if ReadFile returns false than i do WriteFile.
But when it reaches writefile, it throws IO expection:
The process cannot access the file ... because it is being used by another process
You aren't closing the file when you read it.
Put your FileStream and StreamReader objects in using statements:
using (var fs = new FileStream(fname, FileMode.OpenOrCreate,FileAccess.Read)) {
using (var sr = new StreamReader(fs)) {
//read file here
}
}
Make sure you do the same when you write to the file.
You need to dispose the StreamReader object in the ReadFile method. The StreamReader inherits from IDisposable and therfor you need to dispose the object.
Check this link for more info:StreamReader Class

binary serialization to list

I used this information to convert a list to .txt with binary serialization. now I want to load that file, and put it again in my list.
this is my code to convert a list to .txt with binary serialization:
public void Save(string fileName)
{
FileStream fs = new FileStream(#"C:\" + fileName + ".txt", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, list);
fs.Close();
}
so my question is; how to convert this binary file back to a list?
You can do it like this:
//Serialize: pass your object to this method to serialize it
public static void Serialize(object value, string path)
{
BinaryFormatter formatter = new BinaryFormatter();
using (Stream fStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
formatter.Serialize(fStream, value);
}
}
//Deserialize: Here is what you are looking for
public static object Deserialize(string path)
{
if (!System.IO.File.Exists(path)) { throw new NotImplementedException(); }
BinaryFormatter formatter = new BinaryFormatter();
using (Stream fStream = File.OpenRead(path))
{
return formatter.Deserialize(fStream);
}
}
Then use these methods:
string path = #"C:\" + fileName + ".txt";
Serialize(list, path);
var deserializedList = Deserialize(path);
Thanks #Hossein Narimani Rad , I used your answer and changed it a bit (so I understand it more) and now it works.
my binair serialize method (save) is still the same.
this is my binair deserialize method (load):
public void Load(string fileName)
{
FileStream fs2 = new FileStream(fileName, FileMode.Open);
BinaryFormatter binformat = new BinaryFormatter();
if (fs2.Length == 0)
{
MessageBox.Show("List is empty");
}
else
{
LoadedList = (List<Object>)binformat.Deserialize(fs2);
fs2.Close();
List.Clear();
MessageBox.Show(Convert.ToString(LoadedList));
List.AddRange(LoadedList);
}
I know I don't have an exception now, but I understand it better this way.
I also added some code to fill my listbox with my List with the new LoadedList.

How to retrieve integer value from binary file in C#

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

Categories

Resources