简体   繁体   English

如何使用C#将任何数据类型的原始数据写入文件?

[英]How do I write raw data from any data type to a file with C#?

I'm writing a Windows app in C#. 我正在用C#编写Windows应用程序。 I have a custom data type that I need to write as raw data to a binary file (not text/string based), and then open that file later back into that custom data type. 我有一个自定义数据类型,我需要将其作为原始数据写入二进制文件(不是基于文本/字符串的文件),然后再将该文件打开回该自定义数据类型。

For example: 例如:

Matrix<float> dbDescs = ConcatDescriptors(dbDescsList);

I need to save dbDescs to file blah.xyz and then restore it as Matrix<float> later. 我需要将dbDescs保存到文件blah.xyz,然后稍后将其恢复为Matrix<float> Anyone have any examples? 有人有例子吗? Thanks! 谢谢!

As I've mentioned, the options are overwhelming and this question comes with a ton of opinions as far as which one is the best. 正如我已经提到的,选择是压倒性的,这个问题带有很多意见,其中哪一个是最好的。 With that being said, BinaryFormatter could prove to be useful here as it serializes and deserializes object (along with graphs of connected objects) in binary. 话虽如此, BinaryFormatter在这里可以证明是有用的,因为它可以二进制形式对对象(以及连接的对象的图)进行序列化和反序列化。

Here's the MSDN link that explains the usage: https://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter(v=vs.110).aspx 这是解释用法的MSDN链接: https : //msdn.microsoft.com/zh-cn/library/system.runtime.serialization.formatters.binary.binaryformatter(v=vs.110).aspx

Just in case that link fails down the line and because I'm too lazy to provide my own example, here's an example from MSDN: 万一该链接失败了,并且由于我懒得提供自己的示例,下面是MSDN的示例:

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

public class App 
{
    [STAThread]
    static void Main() 
    {
        Serialize();
        Deserialize();
    }

    static void Serialize() 
    {
        // Create a hashtable of values that will eventually be serialized.
        Hashtable addresses = new Hashtable();
        addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
        addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
        addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");

        // To serialize the hashtable and its key/value pairs,  
        // you must first open a stream for writing. 
        // In this case, use a file stream.
        FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

        // Construct a BinaryFormatter and use it to serialize the data to the stream.
        BinaryFormatter formatter = new BinaryFormatter();
        try 
        {
            formatter.Serialize(fs, addresses);
        }
        catch (SerializationException e) 
        {
            Console.WriteLine("Failed to serialize. Reason: " + e.Message);
            throw;
        }
        finally 
        {
            fs.Close();
        }
    }


    static void Deserialize() 
    {
        // Declare the hashtable reference.
        Hashtable addresses  = null;

        // Open the file containing the data that you want to deserialize.
        FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
        try 
        {
            BinaryFormatter formatter = new BinaryFormatter();

            // Deserialize the hashtable from the file and 
            // assign the reference to the local variable.
            addresses = (Hashtable) formatter.Deserialize(fs);
        }
        catch (SerializationException e) 
        {
            Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
            throw;
        }
        finally 
        {
            fs.Close();
        }

        // To prove that the table deserialized correctly, 
        // display the key/value pairs.
        foreach (DictionaryEntry de in addresses) 
        {
            Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
        }
    }
}

Consider the Json.Net package (you can download it to your project via Nuget; the better way, or get it directly from their website ). 考虑一下Json.Net软件包(您可以通过Nuget将它下载到您的项目中;更好的方法是,或者直接从他们的网站获取 )。

JSON is just a string (text) that holds values for complex objects. JSON只是一个字符串(文本),其中包含复杂对象的值。 It allows you to turn many (not all) objects into savable files easily which then can be pulled back. 它使您可以轻松地将许多(不是全部)对象转换为可保存的文件,然后可以将其撤回。 To serialize into JSON with JSON.net: 要使用JSON.net序列化为JSON:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);

And then to deserialize: 然后反序列化:

var product = JsonConvert.DeserializeObject(json);

To write the json to a file: 要将json写入文件:

using (StreamWriter writer = new StreamWriter(@"C:/file.txt"))
            {
                writer.WriteLine(json);
            }

I am not a Web Developer so I am not sure that JSON is Binary. 我不是Web开发人员,所以我不确定JSON是Binary。 Isnt it still text based? 它仍然是基于文本的吗? So here is what I know is a Binary Answer. 所以这就是我所知道的二进制答案。 Hope this Helps! 希望这可以帮助!

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BinarySerializerSample
{
    class Program
    {
        public static void WriteValues(string fName, double[] vals)
        {
            using (BinaryWriter writer = new BinaryWriter(File.Open(fName, FileMode.Create)))
            {
               int len = vals.Length;
               for (int i = 0; i < len; i++)
                   writer.Write(vals[i]);
            }
        }
        public static double[] ReadValues(string fName, int len)
        {
            double [] vals = new double[len];
            using (BinaryReader reader = new BinaryReader(File.Open(fName, FileMode.Open)))
            {

                for (int i = 0; i < len; i++)
                    vals[i] = reader.ReadDouble();
            }
            return vals;
        }

        static void Main(string[] args)
        {
            const double MAX_TO_VARY = 100.0;
            const int NUM_ITEMS = 100;
            const string FILE_NAME = "dblToTestx.bin";
            double[] dblToWrite = new double[NUM_ITEMS];
            Random r = new Random();
            for (int i = 0; i < NUM_ITEMS; i++)
                dblToWrite[i] = r.NextDouble() * MAX_TO_VARY;

            WriteValues(FILE_NAME, dblToWrite);

            double[] dblToRead ;
            dblToRead = ReadValues(FILE_NAME, NUM_ITEMS);

            int j = 0;
            bool areEqual = true;
            while (areEqual && j < NUM_ITEMS)
            {

                areEqual = dblToRead[j] == dblToWrite[j];
                ++j;
            }
            if (areEqual)
                Console.WriteLine("Test Passed: Press any Key to Exit");
            else
                Console.WriteLine("Test Failed: Press any Key to Exit");
            Console.Read();

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM