Context: my end user selects an image from his computer to use as his Profile pic in my C# standalone desktop application. And the backend basically copies the image selected by the end user in the app’s local folder created in User/Documents (also handled in backend).
I want to create a functionality to delete the previous image which was copied to the app’s local folder in the User/Documents and not fill the folder up by keep copying new images.
The RegisterPage.xaml.cs (selection and copying the image)
private void OpenImageFileButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Image files (*.png;)|*.png;";
openFileDialog.InitialDirectory = @"C:"; // Set the initial directory (optional)
if (openFileDialog.ShowDialog() == true)
{
string destinationFilePath;
// Get the selected file path
string selectedImagePath = openFileDialog.FileName;
try
{
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// Create the directory if it doesn't exist
string directoryPath = System.IO.Path.Combine(documentsPath, "FT_SGS", "myschoolinfo");
Directory.CreateDirectory(directoryPath);
// Get the file name from the selected image path
string fileName = System.IO.Path.GetFileName(selectedImagePath);
// Combine the destination folder path with the file name
destinationFilePath = System.IO.Path.Combine(directoryPath, fileName);
// Copy the image file
File.Copy(selectedImagePath, destinationFilePath, true);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.UriSource = new Uri(destinationFilePath, UriKind.RelativeOrAbsolute);
bitmapImage.EndInit();
this.schllogo.Source = bitmapImage;
// Now you can use 'selectedImagePath' as needed (e.g., load it into an Image control)
}
catch (Exception ex)
{
MessageBox.Show($"Error processing image:n{ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
RegisterPage.xaml
<Button Click="RemoveSchlLogo" x:Name="removeschoollogo" Background="{DynamicResource WindowBrush}" Foreground="{DynamicResource Foreground}" Content="Remove logo" Style="{DynamicResource ButtonStyle2}" HorizontalAlignment="Center" VerticalAlignment="Top" Height="38" Width="160" Margin="0,175,0,0"
/>
Alok Nath Jha is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.