C#.net-将文件打包到DAT文件中 [英] C# .net - Packing files into DAT file

查看:76
本文介绍了C#.net-将文件打包到DAT文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何(在C#.net中)将硬盘上的多个文件打包为DAT文件,又如何再次将其解压缩为单个文件?

将在列表框中选择要添加到DAT文件的文件,因此无法读取字节数组和进行串行化.

How would I (in C# .net) pack multiple files on my hard drive into a DAT file, and also unpack into individual files again?

The files to be added to the DAT file will be selected in a list box, so reading to byte arrays and serialazing will not work.

[Serializable]
public class MyObject : ISerializable
{
//The byte arrays would have to be listed here. I don''t see a way to do that, because the program wont know what files to
//pack until runtime when they are selected in the list box.
  public byte[] byteArray1;  public int n2;
  public byte[] bytaArray2;
  public byte[] byteArray3;




如果我对此有误,请纠正我.




Please correct me if im wrong about that.

推荐答案

您好,

您知道要序列化一个类或一个对象.然后您说,有多个文件要写入一个文件,因此您不能使用该方法.我会说你只是知道答案以及如何做(或者说你有能力这样做),但是你对 太懒了 进行操作.

没有冒犯,但是如果是这样,那么开发不适合您:)无论如何,您可以花3分钟时间编写这段代码,并在Google中进行1次搜索即可知道我想要的内容:S坦白地说,并格式化此答案花了我更长的时间:D哈哈

首先,下面是对答案的概述:我所要做的就是将我想要的文件的所有信息放入一个类中,并对该类进行SERIALIZE.是的,很简单.
Hi there,

You know of serializing one class, or rather one object. Then you say, there are multiple files to be written into one file, hence you cannot use that approach. I''d say you just know the answer and how to do it (or rather you possess the capacity to do it) but you are way too lazy to do it.

No offense, but if that is the case, development is not for you :) Anyways, here you go, it just took me 3 minutes to write this code up and 1 search in Google to know what I would want :S Frankly, typing and formatting this answer took me longer :D lol

First off all, an overview of the answer posted below: All I have done is put all information of the files that I want into one class and SERIALIZE that class. Yes, simple like that.
using System;
using System.Runtime.Serialization;

namespace Objects.Serialization
{
    [Serializable()]
    class SelectedFileInfo : ISerializable
    {
        #region Variable(s) & Propert(y/ies)

        public string fileName;
        public byte[] fileData;

        #endregion

        #region Constant(s)

        private const string FileNameField = "FileName";
        private const string FileDataField = "FileData";

        #endregion

        #region Constructor(s)

        public SelectedFileInfo()
        {
            this.fileName = string.Empty;
            this.fileData = null;
        }

        public SelectedFileInfo(SerializationInfo info, StreamingContext context)
        {
            this.fileName = info.GetString(SelectedFileInfo.FileNameField);
            this.fileData = (byte[])info.GetValue(SelectedFileInfo.FileDataField, typeof(byte[]));
        }

        #endregion

        #region ISerializable Members

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            this.retrieveObjectData(info, context);
        }

        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
            this.retrieveObjectData(info, context);
        }

        private void retrieveObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue(SelectedFileInfo.FileNameField, this.fileName);
            info.AddValue(SelectedFileInfo.FileDataField, this.fileData);
        }

        #endregion
    }
}


该类实际上包含所需文件的数据,我仅在该类中放置了2个成员,但是您可以根据需要添加或删除所需的任何内容.创建此类的对象,并为每个文件将数据放入其中(因此,如果有,则5个文件>>> 5个对象,2个文件>>> 2个对象等).


This class is what actually contains the data of the file you want, I''ve only put 2 members in the class, but you can add or remove anything you want, based on your needs. Create an object of this class and put data into it for each file that you have (So if you have, 5 files >> 5 objects, 2 files >> 2 objects, etc.).

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Objects.Serialization
{
    [Serializable()]
    class SelectedFileHolder : ISerializable
    {
        #region Variable(s) & Propert(y/ies)

        public List<selectedfileinfo> fileList; 

        #endregion

        #region Constant(s)

        private const string FileListField = "FileList";

        #endregion

        #region Constructor(s)

        public SelectedFileHolder()
        {
            this.fileList = new List<selectedfileinfo>();
        }

        public SelectedFileHolder(SerializationInfo info, StreamingContext context)
        {
            this.fileList = (List<selectedfileinfo>)info.GetValue(SelectedFileHolder.FileListField, typeof(List<selectedfileinfo>));
        }

        #endregion

        #region ISerializable Members

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            this.retrieveObjectData(info, context);
        }

        void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
        {
            this.retrieveObjectData(info, context);
        }

        private void retrieveObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue(SelectedFileHolder.FileListField, this.fileList);
        }

        #endregion
    }
}



该类将包含您创建的所有SelectedFileInfo对象,并且我们将要对该类进行序列化和反序列化. IE.为每个文件创建的SelectedFileInfo对象将添加到此类的实例.

如果仍然无法理解,请查看我在下面创建的示例.



This is the class which would contain all the SelectedFileInfoobjects you created and it is this class that we are going to serialize and de-serialize. I.e. the SelectedFileInfo objects that created for each file are added to an instance of this class.

If you still don''t get it, look into the example I''ve created below.

// Creating the objects
SelectedFileHolder holder = new SelectedFileHolder();

SelectedFileInfo file1 = new SelectedFileInfo();
file1.fileData = File.ReadAllBytes(@"C:\wamp\license.txt");
file1.fileName = "License Data";
holder.fileList.Add(file1);

// You can add as much as you want, because I have used a List instead of a fixed size array

MessageBox.Show(string.Format("{0} : {1}", holder.fileList[0].fileName, holder.fileList[0].fileData.Length));

// Serializing the "SelectedFileHolder" object
Stream writeStream = File.Open(Form1.SaveFilePath, FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();

bformatter.Serialize(writeStream, holder);
writeStream.Close();

// Deserializing the stored "SelectedFileHolder" object
Stream readStream = File.Open(Form1.SaveFilePath, FileMode.Open);
bformatter = new BinaryFormatter();

SelectedFileHolder newHolder = (SelectedFileHolder)bformatter.Deserialize(readStream);
writeStream.Close();

// Checking the data :)
MessageBox.Show(string.Format("{0} : {1}", newHolder.fileList[0].fileName, newHolder.fileList[0].fileData.Length));



如您所言,您知道我将不解释序列化".如果您需要帮助,请参考此文章 [



Since you said you know I will not be explaining about "Serializing". In case you need help with that refer to this article[^]. It got everything you need to know to achieve what you need and my solution is based on that article too.

Hope this helps :) Regards


我假设您正在询问如何将多个文件压缩为一个输出流.如果您尝试从类文件进行压缩,那么您要做的就是创建一个包含要序列化的类的超类,然后再将该类进行序列化(只要其他类可序列化,它就会工作完成).

如果您试图将不属于程序的多个文件打包在一起,则可以将它们读入字节数组列表中,然后进行序列化.在不了解您要做什么的情况下,这是我能做的最好的事情.

提示,您在问题中输入的信息越多,得到的答案越详细.您可以问的问题长度不受限制.
I assume that you are asking how to compress multiple files into one output stream. If you are trying to compress from class files, all you need to do is create a super class that contains the classes you want to serialize out, and then serialize that class out (as long as the other classes are serializable, it''s job done).

If you are trying to pack multiple files together that aren''t part of a program, you could read them into a list of byte arrays and then serialize that. Without knowing much more about what you are trying to do, this is the best I can do.

As a hint, the more information you put into a question, the more detailed an answer you will get. You aren''t limited in the length of the question that you can ask.


我想说,请保持简单.假设您不需要对主题中的文件进行任何处理,请确定类似
的模式
文件数(Int32)
<文件大小Int32-文件名(为简单起见,每个文件为252个字节)>
的列表 <原始数据>
的列表
例如:

I''d say, keep it simple. Assuming you do not need any processing on files in subject, decide a pattern like

The number of files (Int32)
List of <File Size Int32 - File name (252 bytes for each for simplicty)>
List of <Raw Data>

For instance:

2 Files
36514(File size)  "testfile.txt" + 240 "\0" (filename)
123475(File size) "testfile2.txt" + 239 "\0" (filename)
[your testfile.txt as byte array]
[your testfile2.txt as byte array]



基本要处理的是:



The basic things to deal with are:

// To write
FileStream fileToWrite = File.Open("target.dat",FileMode.Create);
BinaryWriter bw = new BinaryWriter( fileToWrite );
// look BinaryWriter reference for how to write stuff
//And to read
FileStream fileToRead = File.OpenRead("target.dat");
BinaryReader bw = new BinaryReader( fileToRead );
// look BinaryReaderreference for how to read stuff


如果您想参加更高级的课程,请多加关注,以获取更多的学习知识,但又不要浪费信息:)


If you want to get involved with more advanced classes, fine the more you deal with the more you learn but do not choke on information :)


这篇关于C#.net-将文件打包到DAT文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆