C # and storing data in memory

I am using Visual C # .NET, and am creating an application that uses winforms. I need to open several files as strings and manipulate data in different places without saving information back to the file. How do I save this data so that I can use it in different parts of my code?

+5
source share
5 answers

Why open them "like strings"? Strings in .NET are immutable, so they can become expensive if you make a lot of changes. The usual approach would be to parse / deserialize the data into an object model and transfer that object model to your forms - i.e.

MyModel model = MyModel.Load(path);
MyForm form = new MyForm();
form.Model = model;

. :

captionTextBox.Text = model.Title; // etc

, :

captionTextBox.DataBindings.Add("Text", model, "Title");

( , , )

0

, , , , .

public static class MyFilesAsStrings
{
    public static String FirstFile {get;set;}

    public static LoadData() 
    {
        FirstFile = System.IO.File.ReadAllText(@"C:\Temp\MyFile.dat");
        // and so on
    }
}
0

, .

, StringBuilder StringWriter Dictionary, .

, , StringWriter .

, , , , , List .

"copy-to-temp-file-edit-then-copy-back". , , .

0

, , , , , . , .

, , , ( ) . : StringBuilder MemoryStream.

StringBuilder , , . , , StringBuilder.

StringBuilder. , Append(), Insert(), Remove(), Replace() indexer [], . Stringbuilder , , .

You can also load the file into a MemoryStream and then use a StringReader (or StringWriter) to get an interface with a stream (Read (), Peek (), ReadLine (), etc.) to control the string.

This is a bit more work than StringBuilder, but may be preferred if the Stream style approach is better for your application.

0
source

All Articles