EndOfStreamException:无法读取流的末尾(Unity 3d)

时间:2017-11-22 18:16:59

标签: c# unity3d memorystream gzipstream binaryreader

我尝试使用GZipStream解压缩内存中的文件,将解压缩的数据复制到MemoryStream,然后使用BinaryReader(来自Unity 3d)读取MemoryStream。但是,当我尝试运行它时,我收到了这些错误:

EndOfStreamException:无法读取流的末尾。 System.IO.BinaryReader.FillBuffer(Int32 numBytes)(at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/BinaryReader.cs:119) System.IO.BinaryReader.ReadInt32()(at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.IO/BinaryReader.cs:432) LoadNii.LoadNifti(System.String fullPath,Boolean loadFromResources)(在Assets / scripts / LoadNii.cs:240) opengl_main.PrepareNewAnatomy(System.String fullPath,Boolean loadFromResources)(在Assets / scripts / opengl_main.cs:193) opengl_main.LoadFileUsingPath()(在Assets / scripts / opengl_main.cs:656) UnityEngine.Component:SendMessage(String,Object) SimpleFileBrowser.Scripts.GracesGames.FileBrowser:SendCallbackMessage(String)(在Assets / Resources / SimpleFileBrowser / Scripts / GracesGames / FileBrowser.cs:274) SimpleFileBrowser.Scripts.GracesGames.FileBrowser:SelectFile()(在Assets / Resources / SimpleFileBrowser / Scripts / GracesGames / FileBrowser.cs:267) UnityEngine.EventSystems.EventSystem:更新()

有谁知道问题是什么?是否有另一种方法在内存中解压缩文件,并将其传输到binaryReader?感谢

代码:

Stream stream = null;
if (loadFromResources == true)
{
    TextAsset textAsset = Resources.Load(fullPath) as TextAsset;
    Debug.Log(textAsset);
    stream = new MemoryStream(textAsset.bytes);
}
else
{
    FileInfo fi1 = new FileInfo(fullPath);
    if (fi1.Extension.Equals(".gz"))
    {
        stream = new MemoryStream();
        byte[] buffer = new byte[4096];

        using (Stream inGzipStream = new GZipStream(File.Open(fullPath,FileMode.Open), CompressionMode.Decompress))
        {
            int bytesRead;
            while ((bytesRead = inGzipStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                stream.Write(buffer, 0, bytesRead);
            }
        }

    }
    else
        stream = File.Open(fullPath, FileMode.Open);
}
using (BinaryReader reader = new BinaryReader(stream))
{
    //header headerKey substruct:
    headerKey.sizeof_hdr = reader.ReadInt32(); //ERROR
}

2 个答案:

答案 0 :(得分:3)

每次写入流时,其Position都会增加。

写完之后只需设置stream.Position = 0,这样你就可以在之后再次从第一个字节开始读取。

答案 1 :(得分:0)

这只是一个反序列化并返回结果的函数。谢谢@ C.Evenhuis。

          /// <summary>
         ///Get data from a binary file.
        /// </summary>
       /// <param name="filename"></param>
      /// <param name="path"></param>
     /// <returns>Null if no object is found </returns>
        public static T GetData<T>(string filename, string path)
        {
            //Path is empty.
            if (string.IsNullOrEmpty(path)) throw new NullReferenceException("Path can not be null or empty");

            //file is empty.
            if (string.IsNullOrEmpty(filename)) throw new NullReferenceException("File name can not be null or empty.");


            //Storage path
            var storagePath = Path.Combine(path, filename);

            //check file not exist
            if (!File.Exists(storagePath))
                throw new NullReferenceException("No file with the name " + filename + "at location" + storagePath);
            else
                try
                {
                    //create new binary formatter .
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    //Read the file.
                    using (FileStream fileStream = File.Open(storagePath, FileMode.Open))
                    {
                        //result .
                        var result = binaryFormatter.Deserialize(fileStream);
                        //Set file stream to zero .
                        //to avoid Exception: FailedSystem.IO.EndOfStreamException: 
                        //Failed to read past end of stream.
                        fileStream.Position = 0;
                        //Check if casting is possible and raise error accordin to that .
                        return (T)Convert.ChangeType(binaryFormatter.Deserialize(fileStream), typeof(T));

                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Failed" + ex);
                }
        }