How can I create a clone object of streamreader, when i do Serializing on streamreader object, program give me exception :
Unhandled Exception: System.Runtime.Serialization.SerializationException: Type '
System.IO.FileStream' in Assembly 'mscorlib, Version=4.0.0.0, Culture=neutral,
is not marked as serializable.
how can i do this?
suppose i have text file like with the text:
1
2
3
4
5
my program:
[Serializable()]
class Program
{
static void Main(string[] args)
{
Program obj = new Program();
obj.read();
}
void read()
{
StreamReader reader1 = new StreamReader(#"d:\test.txt");
string s = reader1.ReadLine();
Console.WriteLine(s);
SerializeObject("text.txt", reader1);
StreamReader reader2;
for (int i = 0; i < 3; i++)
{
reader1.ReadLine();
}
s = reader1.ReadLine();
Console.WriteLine(s);
reader2 = DeSerializeObject("text.txt");
s = reader2.ReadLine();
Console.WriteLine(s);
}
public void SerializeObject(string filename, StreamReader objectToSerialize)
{
Stream stream = File.Open(filename, FileMode.Create);
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, objectToSerialize);
stream.Close();
}
public StreamReader DeSerializeObject(string filename)
{
StreamReader objectToSerialize;
Stream stream = File.Open(filename, FileMode.Open);
BinaryFormatter bFormatter = new BinaryFormatter();
objectToSerialize = (StreamReader)bFormatter.Deserialize(stream);
stream.Close();
return objectToSerialize;
}
}
I want to output must be:
1
5
2
OK, so you are simply trying to read a file and write to a different file. There is no serialization involved in what you are trying to do. Serialization generally involves persisting objects.
I believe this is what you are after:
static void Main()
{
using(StreamReader reader = new StreamReader(#"d:\input.txt"))
using(StreamWriter writer = new StreamWriter(#"d:\output.txt"))
{
string line;
// Write 1st line
line = reader.ReadLine();
writer.WriteLine(line);
// Skip 3 lines
for (int i = 0; i < 3; i++)
{
reader.ReadLine();
}
// Write 5th & 6th line
for (int i = 0; i < 2; i++)
{
line = reader.ReadLine();
writer.WriteLine(line);
}
}
}
UPDATE
Write the first line, then the fifth line, then the second line:
static void Main()
{
using(StreamReader reader = new StreamReader(#"d:\input.txt"))
using(StreamWriter writer = new StreamWriter(#"d:\output.txt"))
{
string line;
// Write first line
line = reader.ReadLine();
writer.WriteLine(line);
// Read the second line
string second = reader.ReadLine(); ;
// Skip 3rd & 4th lines
for (int i = 0; i < 2; i++)
{
reader.ReadLine();
}
// Write 5th line
line = reader.ReadLine();
writer.WriteLine(line);
// Write the 2nd line
writer.WriteLine(second);
}
}
Related
This question already has an answer here:
When using yield within a "using" statement, when does Dispose occur?
(1 answer)
Closed 1 year ago.
I wrote below code, which works:
//VERSION 1;
static IEnumerable<string> ReadAsLines(string filename)
{
using (StreamReader reader = new StreamReader(filename))
{
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
Using above method:
const string fileData = #"path\to\somePipeDelimitedData.txt";
var reader = ReadAsLines(fileData);
var headerArr = reader.First().Split('|');
foreach (var column in headerArr)
{
var dummy = column;
}
var recordsEnumerable = reader.Skip(1); //skip first header Line
//Read other lines...
foreach (var record in recordsEnumerable)
{
//read each line
var rowArray = record.Split('|');
//etc...
}
Now suppose I start off with a Stream instead of a file;
I tried re-writing the above code, but am struggling with the stream getting closed.
How can I fix the version below?
//VERSION 2;
static IEnumerable<string> ReadAsLines(Stream stream)
{
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
Calling version 2:
byte[] dataByteArr = File.ReadAllBytes(fileData);
MemoryStream memStr = new MemoryStream(dataByteArr);
var reader2 = ReadAsLines(memStr);
var headerArr2 = reader2.First().Split('|'); //*** STREAM gets closed after this line
foreach (var column in headerArr2)
{
var dummy = column;
}
var recordsEnumerable2 = reader2.Skip(1); //skip first header Line
//Read other lines... *** ERROR OCCURS HERE, as the Stream is closed.
foreach (var record in recordsEnumerable2)
{
//read each line
var rowArray = record.Split('|');
//etc...
}
I re-organized my initial attempt by pulling the StreamReader out of the Enumerable method and disposing it outside when I'm really done.
byte[] dataByteArr = File.ReadAllBytes(fileData); //decoded bytes
var memStr = new MemoryStream(dataByteArr);
using (StreamReader sr = new StreamReader(memStr))
{
var dataAsEnumerable = ReadAsLines(sr, memStr);
var headerArr2 = dataAsEnumerable.First().Split('|');
//*** HA! stream is still open !
foreach (var column in headerArr2)
{
var dummy = column;
}
var dataMinusHeader = dataAsEnumerable.Skip(1);
//Read other lines...
foreach (var record in dataMinusHeader)
{
//read each line
var rowArray = record.Split('|');
//etc...
}
}
When the writing starts from one file to the resulting file, the entry passes, and from the second file to this result file is blocked. So in two streams record can not be available in the same time. Error: a process can not access a file because this file is being used by another process. How I can resolve this problem. I tried diffrent ways. For example, If you write directly not to a file from two streams, but add string to some array, and then at the end go through the array and write everything to a file. It must be without synschronized.
class Program
{
public static void WriteOneThread()
{
List<char> listOfChars = new List<char>();
FileInfo file = new FileInfo(#"C:\test\task.txt");
FileStream stream = file.Open(FileMode.Open, FileAccess.ReadWrite);
StreamReader reader = new StreamReader(stream);
string str = reader.ReadToEnd();
Console.WriteLine(str);
char[] arr = str.ToCharArray();
for (int i = 0; i < arr.Length; i++)
{
listOfChars.Add(arr[i]);
}
Console.WriteLine(new string('-', 20));
FileInfo file2 = new FileInfo(#"C:\test\Result.txt");
try
{
foreach (var value in listOfChars)
{
StreamWriter writer = file2.CreateText();
writer.WriteLine(value);
writer.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static void WriteSecondThread()
{
List<char> listOfChars = new List<char>();
FileInfo file = new FileInfo(#"C:\test\pretask.txt");
FileStream stream = file.Open(FileMode.Open, FileAccess.ReadWrite);
StreamReader reader = new StreamReader(stream);
string str = reader.ReadToEnd();
Console.WriteLine(str);
char[] arr = str.ToCharArray();
for (int i = 0; i < arr.Length; i++)
{
listOfChars.Add(arr[i]);
}
Console.WriteLine(new string('-', 20));
FileInfo file2 = new FileInfo(#"C:\test\Result.txt");
try
{
foreach (var value in listOfChars)
{
StreamWriter writer = file2.CreateText();
writer.WriteLine(value);
writer.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static void Main(string[] args)
{
Thread threadOne = new Thread(WriteOneThread);
Thread threadSecond = new Thread(WriteSecondThread);
threadOne.Start();
Thread.Sleep(10000);
threadSecond.Start();
threadOne.Join();
threadSecond.Join();
Console.WriteLine("Запись в файл осуществлена");
Console.ReadKey();
}
}
I wrote a program that reads a PDF file and then shows some information about it. It works fine.
class Program
{
static void Main(string[] args)
{
//some variables
string plabels = null;
string text2Search = "IX";
PdfReader reader = new PdfReader("file.pdf");
string[] labels = PdfPageLabels.GetPageLabels(reader);
for (int l = 0; l < labels.Length; l++)
{
plabels += labels[l] + "\n";
}
Console.WriteLine(plabels.IndexOf(text2Search, StringComparison.CurrentCultureIgnoreCase));
Console.ReadLine();
}
}
I also wrote another program that reads a PDF file and makes a copy of it. It also works fine.
class Program
{
static void Main(string[] args)
{
byte[] bytes;
using (var ms = new MemoryStream())
{
using (var reader = new PdfReader("file.pdf"))
{
using (var stamper = new PdfStamper(reader, ms))
{
}
}
//grab the bytes before closing things out
bytes = ms.ToArray();
}
File.WriteAllBytes("output.pdf", bytes);
}
}
What I cannot do is to combine these two programs into one.
EDIT
Thanks to your comments I spotted an error. Now my code compiles fine, but when run it gives "Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object." The error point to line for(int l = 0; l < labels.Length; l++).
class Program
{
static void Main(string[] args)
{
byte[] bytes;
using (var ms = new MemoryStream())
{
using (var reader = new PdfReader("file.pdf"))
{
//some variables
string plabels = null;
string text2Search = "IX";
string[] labels = PdfPageLabels.GetPageLabels(reader);
for(int l = 0; l < labels.Length; l++)
{
plabels += labels[l] + "\n";
}
Console.WriteLine(plabels.IndexOf(text2Search, StringComparison.CurrentCultureIgnoreCase));
Console.ReadLine();
using (var stamper = new PdfStamper(reader, ms))
{
}
}
//grab the bytes before closing things out
bytes = ms.ToArray();
}
File.WriteAllBytes("output.pdf", bytes);
}
}
reader is already defined in the using statement. You cannot re-use that variable name inside the using block. Change the name of one of the reader variables or get rid of it.
using (PdfReader reader = new PdfReader("file.pdf"))
{
PdfReader reader = new PdfReader("file.pdf"); //is redundant.
}
labels is null. Your PdfPageLabels.GetPageLabels(reader);
is not returning a value so look in there. No code is posted so I can't give you a clearer answer.
I'm trying to make betting program in C#, storing the user's data in a txt file. I have no problem reading the data from it. However, I can't manage to overwrite it.
From what I've tested, if I call the StreamWriter part alone the overwriting happens just fine. When I put the same code after the StreamReader part, the code will reach the Console.WriteLine("reached"); line and ignore everything after it (username is never written in the console). No error is detected and compilation won't stop either.
Here's the class code:
class Dinero
{
private List<string> data;
private string path = #"C:\Users\yy\Documents\Visual Studio 2015\Projects\ErikaBot\ErikaBot\img\bank_data.txt";
...
some other methods here
...
public void thing(string username, int money)
{
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
data = new List<string>();
using (StreamReader sr = new StreamReader(fs))
{
string a = sr.ReadLine();
for (int i = 0; a != null; i++)
{
if (a != username)
{
data.Add(a);
}
else i++;
a = sr.ReadLine();
}
}
string b = Convert.ToString(money);
Console.WriteLine("reached");
using (StreamWriter tw = new StreamWriter(fs))
{
Console.WriteLine(username);
if (data != null)
{
for (int i = 0; i < data.Count; i++)
{
tw.WriteLine(data.ElementAt(i));
}
}
string money2 = Convert.ToString(money);
tw.WriteLine(username);
tw.WriteLine(money2);
}
}
}
By disposing StreamReader you also dispose the FileStream.
Either repeat the filestream initialisation before the using statement for StreamWriter or put the latter in the using statement for StreamReader.
I am reading a file using streamreader opened in ReadWrite mode. The requirement I have is to check for a file for specific text, and if it is found, replace that line with a new line.
Currently I have initialized a StreamWriter for writing.
It is writing text to a file but it's appending that to a new line.
So what should I do to replace the particular line text?
System.IO.FileStream oStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read);
System.IO.FileStream iStream = new System.IO.FileStream(sFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
System.IO.StreamWriter sw = new System.IO.StreamWriter(oStream);
System.IO.StreamReader sr = new System.IO.StreamReader(iStream);
string line;
int counter = 0;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("line_found"))
{
sw.WriteLine("line_found false");
break;
}
counter++;
}
sw.Close();
sr.Close();
Hi Try the below Code.... it will help you....
//Replace all the HI in the Text file...
var fileContents = System.IO.File.ReadAllText(#"C:\Sample.txt");
fileContents = fileContents.Replace("Hi","BYE");
System.IO.File.WriteAllText(#"C:\Sample.txt", fileContents);
//Replace the HI in a particular line....
string[] lines = System.IO.File.ReadAllLines("Sample.txt");
for (int i = 0; i < lines.Length; i++)
{
if(lines[i].Contains("hi"))
{
MessageBox.Show("Found");
lines[i] = lines[i].Replace("hi", "BYE");
break;
}
}
System.IO.File.WriteAllLines("Sample.txt", lines);