コード例 #1
0
        /// <summary>
        /// Handles the click event of btnAdd
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            // Checks if textbox is empty.
            if(!string.IsNullOrWhiteSpace(txtSearchString.Text))
            {
                //Replaces all whitespaces with '%', for us to use in queryURL.
                searchNoWhiteSpaces = txtSearchString.Text.Replace(" ", "%");
                //Creates a new FeedItem.
                FeedItem fItem = new FeedItem(txtSearchString.Text, searchNoWhiteSpaces);
                //Serializes the FeedItem.
                string json = JsonConvert.SerializeObject(fItem);

                //Checks if our file already exists.
                if (File.Exists(CONSTANTS.FEEDITEMPATH + "FeedItem.json"))
                {
                    //File.AppendAllText(CONSTANTS.FEEDITEMPATH + "FeedItem.json", json + ",");
                    fileData = File.ReadAllText(CONSTANTS.FEEDITEMPATH + "FeedItem.json");
                    //Here we check if our document ends with ']'
                    if (fileData.EndsWith("]"))
                    {
                        //If it ends with ']', then remove it, and replace it with ','
                        fileData = fileData.Remove(fileData.Length - 1);
                        fileData = fileData + ",";
                        //Write to our file again.
                        File.WriteAllText(CONSTANTS.FEEDITEMPATH + "FeedItem.json", fileData);
                    }
                    File.AppendAllText(CONSTANTS.FEEDITEMPATH + "FeedItem.json", json + ",");
                }
                else
                {
                    //If our file doesn't exists already, then we'll have to start our file with a ']', to have a valid JSON
                    File.AppendAllText(CONSTANTS.FEEDITEMPATH + "FeedItem.json", "[");
                    File.AppendAllText(CONSTANTS.FEEDITEMPATH + "FeedItem.json", json + ",");
                }
                //Sets the dialogresult to true
                DialogResult = true;
                //Closes the windows.
                this.Close();
            }
        }