序列化正在覆盖文件
Serialization is overwriting to the file
我创建了一个class来创建从用户读写的进程。有人可以帮助我为什么它正在写入文本文件但它正在覆盖自己吗?
[Serializable]
class FileReadWrite<TFile>
{
static Stream stream;
static IFormatter formatter = new BinaryFormatter();
//Writing to text file
public static void SerializeData(List<TFile> objectToSerialize, string filePath)
{
stream = new FileStream(filePath, FileMode.Create);
formatter.Serialize(stream, objectToSerialize);
Console.WriteLine("Account Created SuccessFully!");
stream.Close();
}
}
需要FileMode.Append。根据 doc:
Opens the file if it exists and seeks to the end of the file, or
creates a new file. This requires Append permission. FileMode.Append
can be used only in conjunction with FileAccess.Write. Trying to seek
to a position before the end of the file throws an IOException
exception, and any attempt to read fails and throws a
NotSupportedException exception.
所以解决方案是:
stream = new FileStream(filePath, FileMode.Append);
或者您可以像这样进行显式检查:
if(!File.Exists(fileName))
{ // create a new file
}
else //Append to a file
问题不是很清楚可能这是你想做的:
使用 (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write))
我创建了一个class来创建从用户读写的进程。有人可以帮助我为什么它正在写入文本文件但它正在覆盖自己吗?
[Serializable]
class FileReadWrite<TFile>
{
static Stream stream;
static IFormatter formatter = new BinaryFormatter();
//Writing to text file
public static void SerializeData(List<TFile> objectToSerialize, string filePath)
{
stream = new FileStream(filePath, FileMode.Create);
formatter.Serialize(stream, objectToSerialize);
Console.WriteLine("Account Created SuccessFully!");
stream.Close();
}
}
需要FileMode.Append。根据 doc:
Opens the file if it exists and seeks to the end of the file, or creates a new file. This requires Append permission. FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek to a position before the end of the file throws an IOException exception, and any attempt to read fails and throws a NotSupportedException exception.
所以解决方案是:
stream = new FileStream(filePath, FileMode.Append);
或者您可以像这样进行显式检查:
if(!File.Exists(fileName))
{ // create a new file
}
else //Append to a file
问题不是很清楚可能这是你想做的: 使用 (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write))