private void SwitchBackground() { lock (_lockObject) { var query = _viewModel.GetQuery(); if (!WallhavenAPI.API.IsLoggedIn() && !String.IsNullOrEmpty(_viewModel.Username) && !String.IsNullOrEmpty(_viewModel.Password)) { if (!WallhavenAPI.API.Login(_viewModel.Username, _viewModel.Password)) { MessageBox.Show("Couldn't log in with the credentials supplied, please try again, or clear the credential boxes."); return; } } var results = WallhavenAPI.API.Search(query); if (results.Any()) { var img = WallhavenAPI.API.GetFile(results[0]); var imageFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WallhavenBGBot"); if (!Directory.Exists(imageFolder)) { Directory.CreateDirectory(imageFolder); } var filepath = Path.Combine(imageFolder, results[0].Split('/').Last()); File.WriteAllBytes(filepath, img); BackgroundHelper.UpdateBackground(filepath); if (_viewModel.AutomaticallyCleanAppDataFolder) { var oldFiles = Directory.GetFiles(imageFolder).Where(x => x != filepath).ToList(); foreach (var item in oldFiles) { File.Delete(item); } } } } }