简体   繁体   English

C#File.ReadAllText()不返回当前文件内容

[英]C# File.ReadAllText() not returning current file content

I am having trouble reading a json config file from my filesystem. 我无法从文件系统中读取json配置文件。 I am serializing an object to file like this: 我正在将对象序列化为这样的文件:

string json = JsonConvert.SerializeObject(Settings.Instance);
Directory.CreateDirectory(configFileDir);
File.WriteAllText(configFileDir + configFilePath, json);

The full path is 完整的路径是

C:\Users\username\Documents\MyApp\config.json

Now I can read it with these lines: 现在,我可以通过以下几行阅读它:

string json = File.ReadAllText(configFileDir + configFilePath);                
Instance = JsonConvert.DeserializeObject<Settings>(json);

My problem is that it seams that it won't correctly read some properties after I built a new version of the program. 我的问题是,它表明在我构建了新版本的程序后,它无法正确读取某些属性。 When I just restart, all the settings are loaded fine, but when I rebuilt, the file won't load longer string values (tokens). 当我重新启动时,所有设置都可以正常加载,但是当我重建时,该文件将不会加载更长的字符串值(令牌)。

A print of the json string shows empty string values for some keys which clearly have values when the file is opened in notepad. json字符串的打印显示某些键的空字符串值,当在记事本中打开文件时,这些键显然具有值。

Does anyone has a guess? 有人猜吗?

Greetings, Maik 问候,迈克

EDIT: 编辑:

The json looks like this: json看起来像这样:

{
"DisplayLanguage": "en-US",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjM4OWZmMTIxZWU1MmI1ZDk3NWEzY2E0NzYwN2JiZTIzODc1ZjViMDUxNzY1ZDE1MGExZDgyNTM0ODUyMjE4MTcxOGQ0ZTA2NTZlM2JhYzg5In0.eyJhdWQiOiJmNWIwYjcwMS01ODEzLTQ5OGMtYmE1NS1kMWZhOGM5YzQxMGUiLCJqdGkiOiIzODlmZjEyMWVlNTJiNWQ5NzVhM2NhNDc2MDdiYmUyMzg3NWY1YjA1MTc2NWQxNTBhMWQ4MjUzNDg1MjIxODE3MThkNGUwNjU2ZTNiYWM4OSIsImlhdCI6MTUzNzI4NDA0MCwibmJmIjoxNTM3Mjg0MDQwLCJleHAiOjE1Njg4MjAwNDAsInN1YiI6ImE1MTk2OTNjLTAzMGMtNDdjMi04MGI5LTZiNTc5YmQ3MzZlNSIsInNjb3BlcyI6W119.yjzApeU54uXch-3V-x82V-mXfmyr-HG0LsxQMG74nrJP_dBmSi8MuB5mD3Zc07qRnmKnyep7YGYVdhvmukALIY4u5lXrVGXFx_U_EWMyEKce9BxMrM9qbqy-oZ5hfJ9rogUsKeQakkpnD4yciTqn0h8sg-uo6H0-pcWIubhWA9OYmU5-vAIhVRJrQBggW305auCiyKVYcoRQowf12RJhrudn8F_eOhEbrV4A9PZVHTIIVRRFFTCfcHNYDsW9cS1RJ07sOE_rg8-yjQt74gmClgZguYngjQiukCsJtzMBRywRUT24DPGauPsAyYHWzitfe-KaGBbUSLFr2YOK3cDhZI7POv6QaFH-iIcw2-2iTR_h2_rk_iVYQNsyv0lU9KglrsUjiAonqESyHvAyYcSVDaqRobDdG9iXSpKw4jDSL7vkt7_IkMQ1cCftvqueglDNosygR6zbmi4L7ESW5eia8n_6-q6tkSaPageupXXmEBMBZNQF_p8HQf9J8ma7hxc-bcPGFkHFFBhrWlTJg62fT9AR9wIq7zueYpamxkGgfZnXF9QMzEjXNobs3paF9pouTv7H6v1iHJ_90WpGe3NVnJTHxPWVImtb9npvfPgWcYE8Trz6xoTbE81Al5fLjrAK7antgS0DkYkzMp1rxSUQxw_qwTLywuFJJLcwhY5mY2s",
"GUID": "993bc5f2-0b2b-48da-8fc7-94a7b96dc322",
"sortedByRating": true,
"lists": ""
}

Only token and GUID seem to lose its values, DisplayLanguage and the others load just fine. 只有令牌和GUID似乎会丢失其值,DisplayLanguage和其他加载就很好了。 I print the json with log4net, this is not the problem. 我用log4net打印json,这不是问题。 I get the filepath with: 我得到的文件路径:

private static readonly string configFileDir = Path.Combine(Environment.ExpandEnvironmentVariables("%userprofile%"), "Documents") + @"\MyApp";
private static readonly string configFilePath = @"\config.json";

Settings class looks like this: 设置类如下所示:

public class Settings
{
    private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    private static readonly string configFileDir = Path.Combine(Environment.ExpandEnvironmentVariables("%userprofile%"), "Documents") + @"\MyApp";
    private static readonly string configFilePath = @"\config.json";

    private static Settings _instance;

    public static Settings Instance
    {
        get { return _instance ?? (_instance = new Settings()); }
        private set { _instance = value; }
    }

    [JsonIgnore]
    public static readonly string AddInVersion = "1.4.0.3";

    [JsonProperty("DisplayLanguage")]
    public static string DisplayLanguage { get; set; } = "";

    [JsonProperty("token")]
    public static string AuthToken { get; set; } = "";

    [JsonProperty("GUID")]
    public static string GUID { get; set; } = "";

    [JsonProperty("sortedByRating")]
    public static bool RecommendationsSortedByRating { get; set; } = true;

    [JsonProperty("DistLists")]
    public static string DistLists { get; set; } = "";

    public static void Load()
    {
        try
        {
            log.Info("trying to read config file: " + configFileDir + configFilePath);

            string json = File.ReadAllText(configFileDir + configFilePath);
            log.Info("read: " + json);

            Instance = JsonConvert.DeserializeObject<Settings>(json);
            log.Info("Config file loaded!");
            log.Debug(JsonConvert.SerializeObject(Instance, Formatting.Indented));

        }
        catch (Exception)
        {
            log.Info("Config file not found or could not be loaded. Using Default Settings");
        }
    }

    public static void Save(string settingToSave = "")
    {
        try
        {
            string json = JsonConvert.SerializeObject(Settings.Instance, Formatting.Indented);
            Directory.CreateDirectory(configFileDir);
            File.WriteAllText(configFileDir + configFilePath, json);
            log.Info("Config file successfully saved! (" + settingToSave + ")");
        }
        catch (Exception)
        {
            log.Error("Config file could not be saved!");
        }
    }

It is not path issue you are reading file very well. 您正在很好地阅读文件不是路径问题。 check setting class 检查设定等级

public class Settings{
public string DisplayLanguage{ get; set; }
public string token{ get; set; }

 }

if you miss any of them it can create issue. 如果您错过其中任何一个,可能会造成问题。 check formats also. 还检查格式。 Log4net may not display long string. Log4net可能不显示长字符串。 Try to check upper case sentence case of token in class. 尝试检查类中标记的大写句子大小写。

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

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