读取文件并将其保存在内存中 [英] Read file and save it in memory

查看:150
本文介绍了读取文件并将其保存在内存中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用一个自定义的.xml设置文件,我从中读取了一些内容.现在,它每次都会从文件中读取数据,并且会影响性​​能.将文件保存到缓存中并从中读取的最佳方法是什么?

My application uses a custom .xml settings file which I read some stuff from. As it is now it reads from the file every time and it effects performance. What is the best way of save the file into the cache and read from there instead?

public static class SettingsReader {
    private static XDocument SettingsFile = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + "\\Settings.xml");
}

推荐答案

我通常声明一个设置类.然后,在启动时,我读取配置文件并将其反序列化为Settings对象,并将其保留在静态变量中.

I usually declare a settings class. Then at startup I read configuration file and deserialize it into a Settings object and keep it in a static variable.

通过这种方式,您只需从任何地方访问属性即可访问设置.

This way you can reach to your settings just by accessing a property from everywhere.

public class MySettings {
    public string RemoteServerAddress { get; set; }
    public int TcpCommunicationTimeout { get; set; }
}

public class Program {
    public readonly static MySettings ProgramSettings { get; private set; }

    static void Main(string[] args) {
        var serializer = new System.Xml.Serialization.XmlSerializer(typeof(MySettings));
        using(var stream = System.IO.File.OpenRead("config file path")){
            Program.ProgramSettings = (MySettings)serializer.Deserialize(stream);
        }
        SomeMethod();
    }

    static void SomeMethod(){
        if (Program.ProgramSettings.TcpCommunicationTimeout > 5) {
            ...
        }
    }
}

这篇关于读取文件并将其保存在内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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