如何创建streamreader的克隆对象,当我在streamreader对象上进行序列化时,程序给我异常:
未处理的异常:System.Runtime.Serialization.SerializationException:Type' 在Assembly'mscorlib中的System.IO.FileStream',Version = 4.0.0.0,Culture = neutral, 未标记为可序列化。
我该怎么做?
假设我的文本文件与文本一样:
1
2
3
4
5
我的节目:
[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;
}
}
我想输出必须是:
1
5
2
答案 0 :(得分:1)
好的,所以你只是想读取一个文件并写入另一个文件。您尝试执行的操作不涉及序列化。序列化通常涉及持久化对象。
我相信这就是你所追求的:
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);
}
}
}
<强>更新强> 写第一行,然后写第五行,然后写第二行:
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);
}
}