예! 이제 더 많은 연구를 한 후에 좋은 해결책을 얻었습니다. 필자는 "바이트 배열을 FileStream에 읽는 법"을 게시했습니다. 바이트 배열을 FileStream으로 읽어 들일 수는 없지만, 드라이버에서 바이트 배열로 파일을 읽는 데만 사용됩니다. 그래서 코드에 약간의 변화가 생겼습니다. 이제 FileStream을 사용하여 파일을 읽습니다. 어떻게 파일을 만들었습니까?
이 컨텍스트에서 나는 개체가 있습니다. 개체는 당신이 원하는대로 무엇이든됩니다!
나는 컬렉션을 신 s 오브젝트로 사용합니다.
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;
}
: 그래서이 방법을 쓰기 않습니다. 어떤 도움을 주셔서 너무 감사드립니다.
왜 FileStream 대신 MemoryStream을 사용하지 않습니까? – Tomtom
MemoryStream은 LoadFile 메서드에서 FileStream으로 사용할 수 있습니까? –
코드를 컴파일하는 'FileStream'은 constuctor에서 0 개의 인수를 취하지 않습니다. –