Save array to file

I have a string array filled with thousands of records. I want the fastest way to save this data to disk and load it back.

I am currently browsing an array and adding this data to a string, and then storing that string. It takes a lot of time.

What is the fastest / most efficient way to do this?

thanks

+4
source share
4 answers

Write

Dim FileName as string=Application.StartupPath & "\myarray.txt" IO.File.WriteAllLines(FileName,myarray) 

Read

  Dim FileName as string=Application.StartupPath & "\myarray.txt" Dim myarray() As String = File.ReadAllLines(FileName) 
+5
source

How important is the resulting file to be readable? If this is mostly read later by the program, you should definitely use serialization:

 public void SaveArray (string[] array) { NetDataContractSerializer serializer = new NetDataContractSerializer(); using (FileStream file = System.IO.File.Create(_filename)) { serializer.Serialize(file, array); } } 

Edit:

To summarize the advantages of this method compared to the other two proposed below, the first uses StringBuilder to concatenate a large string and then save it to disk, and the second using WriteAllLines to write an array of strings to disk:

The first method will completely lose faithfulness to the original list of strings, since it will combine them into one string. Can you split them later? Are there well-known delimiters between them? Not necessary. This is more efficient than just calling + between them, but this is not a very good way to store them.

The second way is better, since each line will be saved on a different line and can be read using ReadAllLines, but you are still on shaky ground. What happens if a line contains a NewLine character? This will be one line when writing, but two different lines when reading. Again, the WriteAllLines / ReadAllLines call relies on newlines that are good delimiters, if not necessary.

Using a serializer - and it doesn't matter if it will be a NetDataContractSerializer, BinaryFormatter or any other - will maintain complete accuracy with your original data structure, with only a bit of overhead.

0
source

Try using StringBuilder

See msdn link for more

Why stringbuilder?

When working with large files. It is advisable to use the StringBuilder class, rather than a regular string class. Adding lines together requires the old line to be copied to the new line. String Builders are buffers that can easily resize, and you can add and remove faster.

-one
source

You have to scroll through your data with a string builder, which is much faster than a regular string.

then create a write / read stream (when you want to download the file) from the I / O library and create the file on your disk.

-one
source

Source: https://habr.com/ru/post/1398183/


All Articles