-2

我目前正在制作一个简单的工具,允许您一次进行不同类型的搜索。到目前为止,我已经通过实现一个 Site 类、创建一个我想要搜索的站点列表、然后打开一个带有 Browser 元素的新窗口以及每个活动站点所需的搜索 URL 来完成此操作。

还有一种方法可以创建一个新站点并将其添加到列表中。

网站.cs

public class Site
    {
        public int type { get; set; }
        public string URL { get; set; }
        public string extras { get; set; }
        public string name { get; set; }
        public bool IsChecked { get; set; }
    

        public Uri GetMySearch(string query)
        {
            switch (type)
            {
                case 0: //Simple Search
                    return new Uri(URL + query);
                case 1: //API call
                    return new Uri(URL + query + extras);
                default: return null;
            }
        }
    }

Mainwindow.Cs 的某些部分

        private void Window_Loaded(object sender, RoutedEventArgs e)   //initialization
        {
            Site Google = new Site();
            Google.URL = "https://google.com/search?q=";
            Google.type = 0;
            Google.name = "google";

            Site Wolfram = new Site();
            Wolfram.URL = "https://api.wolframalpha.com/v1/simple?i=";
            Wolfram.type = 1;
            Wolfram.extras = "&appid=2GA4A5-YL7HY9KR42";
            Wolfram.name = "Wolfram";

            Site Wikipedia = new Site();
            Wikipedia.URL = "https://google.com/search?q=site:wikipedia.org";
            Wikipedia.type = 0;
            Wikipedia.name = "Wikipedia";

            sites.Add(Google);
            sites.Add(Wolfram);
            sites.Add(Wikipedia);

            SitesDisplay.ItemsSource = sites;
        }

        private void AddNewSiteButton(object sender, RoutedEventArgs e)
        {
            SiteEntryWindow siteEntryWindow = new SiteEntryWindow("Enter the display name of your site \nOr leave blank to default to URL");
            if (siteEntryWindow.ShowDialog() == true)
            {
                if (siteEntryWindow.url.Length > 3)
                    AddASite(siteEntryWindow.url, siteEntryWindow.MyName);
                else MessageBox.Show("Please enter a valid url!", "Oops!", MessageBoxButton.OK, MessageBoxImage.Error);

            }
           
        }

        public void AddASite(string url, string name = "")
        {
            Site mySite = new Site();
            if (name.Length > 0)
                mySite.name = name;
            else mySite.name = url;
            mySite.URL = "https://google.com/search?q=site:" + url;
            mySite.type = 0;
            sites.Add(mySite);
            SitesDisplay.ItemsSource = null;
            SitesDisplay.ItemsSource = sites;
        }

本质上,我试图弄清楚如何将站点的用户列表保存到 txt 文件(或在这种情况下更适用的文件),然后在应用程序打开时加载它。我尝试使用 StreamWriter 和 WriteAllLines,但由于它是网站列表,他们不知道该怎么做。

我可能会使用大量 if else 将每个单独的类属性处理为字符串,然后将其写入 txt 文件,但每当我想加载时我都必须解析它,我无法想象这会很容易。

这个人似乎遇到了类似的问题,但我不确定 XML 文件是否是最好的解决方案,而且XmlSerializer似乎超出了我的范围。有没有更简单/更好的方法来做到这一点?

如果这是一个愚蠢的问题或有一个简单的解决方案,我对 C# 和 WPF 仍然有些陌生,很抱歉。

4

1 回答 1

1

您可以将您的Site集合序列化为 JSON 并将 JSON 对象保存到文件中(BinaryFormatter出于安全原因已过时)。

以下示例使用System.Text.Json.JsonSerializer并需要对添加到项目中的“System.Text.Json.dll”的引用。如果您未使用 .NET Core >=3.0 或 .NET 5.0,则可以使用 NuGet 包管理器安装包(以防无法通过参考浏览器获得程序集)。

private async Task SerializeToFileAsync<TValue>(TValue valueToSerialize, string destinationFilePath)
{
  string jsonData = System.Text.Json.JsonSerializer.Serialize(valueToSerialize);
  using (var destinationFile = new FileStream(destinationFilePath, FileMode.Create))
  {
    using (var streamWriter = new StreamWriter(destinationFile))
    {
      await streamWriter.WriteAsync(jsonData);
    }
  }
}

private async Task<TValue> DeserializeFromFileAsync<TValue>(string sourceFilePath)
{
  using (var sourceFile = new FileStream(sourceFilePath, FileMode.Open))
  {
    using (var streamReader = new StreamReader(sourceFile))
    {
      string fileContent = await streamReader.ReadToEndAsync();
      return System.Text.Json.JsonSerializer.Deserialize<TValue>(fileContent);
    }
  }
}

例子

var sites = new List<Site>
{
  new Site
  {
    Google.URL = "https://google.com/search?q=",
    Google.type = 0,
    Google.name = "google"
  }
};

// Save list of Site to "sites.txt"
await SerializeToFileAsync(sites, "sites.txt");

// Load list of Site from "sites.txt"
List<Site> sites = await DeserializeFromFileAsync<List<Site>>("sites.txt");
于 2020-09-24T07:22:30.043 回答