C# 如何将字节数组读入 FileStream

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15292407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:19:04  来源:igfitidea点击:

How to read byte array into FileStream

c#

提问by Tri Nguyen Dung

I have an byte array and I want to read the byte array into a FileStream. Below is my sample of code:

我有一个字节数组,我想将字节数组读入 FileStream。下面是我的代码示例:

string fileName = "test.txt";
byte[] file = File.ReadAllBytes(Server.MapPath("~/Files/" + fileName));
FileStream fs = new FileStream();
fs.ReadByte(file);
object obj = LoadFile<object>(fs);

public static T LoadFile<T>(FileStream fs)
{
    using (GZipStream gzip = new GZipStream(fs, CompressionMode.Decompress))
    {
        BinaryFormatter bf = new BinaryFormatter();
        return (T)bf.Deserialize(gzip);
    }
}

In the method above, I have use FileStream to read byte array, but unlucky fs.ReadByte cannot read byte array. Any help please focus on how to Read byte array into a FileStream for using as a parameter in method "LoadFile". Please do not read directly the file into FileStream because the file here is loaded from somewhere else like from database or other source.

在上面的方法中,我使用 FileStream 读取字节数组,但不幸的是 fs.ReadByte 无法读取字节数组。任何帮助请关注如何将字节数组读入 FileStream 以用作方法“LoadFile”中的参数。请不要直接将文件读入 FileStream,因为这里的文件是从其他地方加载的,比如从数据库或其他来源。

采纳答案by G Ravinder

string fileName = "test.txt";
byte[] file = File.ReadAllBytes(Server.MapPath("~/Files/" + fileName));
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);

回答by Matten

Why do you run File.ReadAllBytesprior to the usage of your FileStream?

为什么File.ReadAllBytes在使用之前运行FileStream

string fileName = "test.txt";
using(FileStream fs = new FileStream(Server.MapPath("~/Files/" + fileName), FileMode.Open, FileAccess.Read))
{
    object obj = LoadFile<object>(fs);
    fs.Close();
}

回答by usr

I'm not sure where the misunderstanding is. FileStream represents a file on disk. You cannot "read bytes into it" without writing them to disk and you cannot read from it without reading from disk.

我不确定误解在哪里。FileStream 代表磁盘上的文件。如果不将字节写入磁盘,就无法“将字节读入其中”,如果不从磁盘读取,则无法从中读取字节。

Maybe what you want is a MemoryStream which can contain arbitrary contents.

也许您想要的是一个可以包含任意内容的 MemoryStream。

Both derive from Stream.

两者都源自 Stream。

回答by Tri Nguyen Dung

Yeah! Now I got a good solution after doing some more research. As the topic I have posted "How to read byte array into FileStream". We cannot read byte array into FileStream, it just use to read a file on driver to byte array. So I have change a little bit on my code, and now I have a file to read it using FileStream. How I made a file?

是的!现在我做了一些更多的研究后得到了一个很好的解决方案。作为主题,我发布了“如何将字节数组读入 FileStream”。我们不能将字节数组读入 FileStream,它只是用于将驱动程序上的文件读入字节数组。所以我对我的代码做了一些更改,现在我有一个文件可以使用 FileStream 读取它。我如何制作文件?

In this context I have an object. The object is anything as you want!

在这种情况下,我有一个对象。对象是你想要的任何东西!

I use a collection as a samble object.

我使用集合作为 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();
}

After I have wrote my object to a file, I need a method to read it back to object. So I do write this method:

将对象写入文件后,我需要一种方法将其读回对象。所以我写了这个方法:

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;
}

After doing some steps above, I am now can write any type object to file and then read it back to original object. Thank too much for any help I have got there.

完成上述一些步骤后,我现在可以将任何类型的对象写入文件,然后将其读回原始对象。非常感谢我在那里得到的任何帮助。