1

我正在尝试编写一个简单的天气应用程序作为我的第一个应用程序。我必须尽可能减少 http 请求的数量,因此我在应用程序中使用了 isolatedStorageSetting 来保存请求的数据以及上次请求的日期和时间。在应用程序开始一个请求之前,它会在这个文件中查看最后一个请求是什么时候,如果 120 分钟过去了,就开始一个新的请求。所有这些都在应用程序中完美运行,但现在我必须实施计划任务来更新动态磁贴并在后台锁定屏幕。但在后台代理请求数据之前,它必须查看此文件以请求最后一次更新并在请求后重写数据。所以我需要的是一个可以被app和后台代理读写的文件。我现在需要一个互斥锁并继续...但我的问题是

  1. 对于这种情况,正确的文件或数据库类型是什么?(isolatedStorgeSettings、isolatedStorgeFile 或其他)

  2. 我必须在哪里生成这个文件?(在 MainPage.xaml.cs 中还是我需要一个 Class Lib. Project)

  3. 从应用程序和后台代理读取和写入此文件中的条目的语法如何?

好的,我现在有这个例子,作为逐步理解洞主题的测试......

  1. 我有一个类库“DataLib”,其中包含:

    命名空间数据库 { 公共类数据库 {

    public static string DatenHolen(string DatenPacket)
    {
        IsolatedStorageFile WetterDatenDatei = IsolatedStorageFile.GetUserStoreForApplication();
    
        try
        {
            //Create == Create OR Overwrite
            IsolatedStorageFileStream myStream = new IsolatedStorageFileStream("datei1.txt", System.IO.FileMode.Create, WetterDatenDatei);
            StreamWriter writer = new StreamWriter(myStream);
            writer.Write("Inhalt der Datei");
            writer.Close();
        }
        catch (Exception)
        {
            MessageBox.Show("Fehler beim Schreiben der Datei");
        }
    
        try
        {
            IsolatedStorageFileStream myStream = new IsolatedStorageFileStream("datei1.txt", System.IO.FileMode.Open, WetterDatenDatei);
            StreamReader reader = new StreamReader(myStream);
            DatenPacket = reader.ReadToEnd();
            reader.Close();
        }
    
        catch (Exception)
        {
            MessageBox.Show("Fehler beim Auslesen der Datei");
        }
    
        return DatenPacket;
    }
    

    } }

  2. 我的应用程序本身带有 MainPage.xaml.cs,它引用了 DataLib 并包含以下内容:

    使用数据库;

...

txt_Test.Text = DataLib.DataLib.DatenHolen();

此行产生错误。我只是不会在文本框“txt_Test”中显示生成的字符串。我的错误在哪里?

4

2 回答 2

2

您可以将设置保存在您的应用程序中,并通过将文件保存到独立存储让您的​​后台代理访问它们。我使用 JSON.Net 来保存和读取文件。我总是将我的设置保存在我的存储空间的 .\Shared\ 中。这样我就知道我可以随时访问它。我创建了一个名为FileStorage的用于存储和读取此信息的类。使用这个类,你可以很容易地保存你的设置。我将在我的设置中创建一个保存和加载方法,以便可以使用当前信息读取和更新它们。

public class AppSettings
{
    public bool SomeProp { get; set; }
    public double AnotherProp { get; set;}

    public void Save()
    {
        FileStorage.WriteSharedData("Settings.txt", this);
    }

    public static AppSettings Load()
    {
        return FileStorage.ReadSharedData<AppSettings>("Settings.txt");
    }
}

此类有助于确保我可以毫无问题地访问文件和我的设置。

为我的应用程序和后台代理使用 IsolatedStorageSettings 时,我取得了成功。如果内存是一个问题,我只使用 IsolatedStorageSettings,因为我的其他解决方案使用 JSON.Net,它会消耗相当多的内存。

于 2014-01-08T23:39:25.080 回答
1
  1. 使用isolatedStorage,但不使用isolatedStorageSettings。用 Mutex 保护它,不会有问题。
  2. 在需要的地方生成它。
  3. 最简单的方法是XmlSerializer

2:设置访问:

public new static App Current
{
    get
    {
        return (App)Application.Current;
    }
}

static public MySettings mySettings = new MySettings();

现在您可以通过以下方式访问所需的设置:

App.Current.mySettings.Save() // Load() ... etc.
于 2014-01-07T11:03:03.720 回答