是的!现在我做了更多的研究后得到了一个很好的解决方案。作为我发布的主题“如何将字节数组读入 FileStream”。我们不能将字节数组读入 FileStream,它只是用来将驱动程序上的文件读入字节数组。所以我对我的代码进行了一些更改,现在我有一个文件可以使用 FileStream 读取它。我是如何制作文件的?
在这种情况下,我有一个对象。对象是你想要的任何东西!
我使用集合作为 samble 对象。
Collection<object> list = new Collection<object>();
//Now I will write this list to a file. fileName is what you want and be sure that folder Files is exist on server or at the root folder of your project
WriteFile(list, Server.MapPath("~/Files/" + fileName));
//The method to write object to file is here
public static void WriteFile<T>(T obj, string path)
{
FileStream serializeStream = new FileStream(path, FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(serializeStream, obj);
serializeStream.Flush();
serializeStream.Close();
}
将对象写入文件后,我需要一种方法将其读回对象。所以我确实写了这个方法:
public static Collection<object> ReatFile(string fileName){
//I have to read the file which I have wrote to an byte array
byte[] file;
using (var stream = new FileStream(Server.MapPath("~/Files/" + fileName), FileMode.Open, FileAccess.Read))
{
using (var reader = new BinaryReader(stream))
{
file = reader.ReadBytes((int)stream.Length);
}
}
//And now is what I have to do with the byte array of file is to convert it back to object which I have wrote it into a file
//I am using MemoryStream to convert byte array back to the original object.
MemoryStream memStream = new MemoryStream();
BinaryFormatter binForm = new BinaryFormatter();
memStream.Write(file, 0, file.Length);
memStream.Seek(0, SeekOrigin.Begin);
Object obj = (Object)binForm.Deserialize(memStream);
Collection<object> list = (Collection<object>)obj;
return list;
}
完成上述一些步骤后,我现在可以将任何类型的对象写入文件,然后将其读回原始对象。非常感谢我在那里得到的任何帮助。