I am currently working on a Blend application with C#, in which i display the images in a certain directory. I try to alter the name of the Image file i display on my UI with a Button click event.
Initialization of the ListBox item where user chooses which image to be displayed:
public MainWindow()
{
InitializeComponent();
string[] images = Directory.GetFiles(PhotoDir);
foreach (string imagePath in images)
{
MediaListBox.Items.Add(imagePath);
}
}
OnSelectedChanged event of my ListBox:
private void MediaListBoxSelectedChanged(object sender, SelectionChangedEventArgs e)
{
ImagePreviewBox.Source = new BitmapImage(new Uri(MediaListBox.SelectedValue.ToString()));
}
The button click event i implemented which sets the source of the Image to null beforehand, then tries to rename the file and the corresponding ListBox line and then display the image again into the Image:
private void SubmitClicked(object sender, RoutedEventArgs e)
{
ImagePreviewBox.Source = null;
string directory = System.IO.Path.GetDirectoryName(MediaListBox.SelectedValue.ToString());
string newFilePath = System.IO.Path.Combine(directory, newFileName);
File.Move(MediaListBox.SelectedValue.ToString(), newFilePath);
MediaListBox.Items[MediaListBox.SelectedIndex] = newFilePath;
ImagePreviewBox.Source = new BitmapImage(new Uri(MediaListBox.SelectedValue.ToString()));
}
I have received :
System.IO.IOException: 'The process cannot access the file because it is being used by another process.'
When i was debugging the code, i have realized that after executing the line in which i am setting the ImagePreviewBox.Source = null i still could see the image being displayed. I have added Thread.Sleep() which also did not work, also tried to move that operation to a different button's OnClick event so that i can see it is no longer being used by the Image control:
private void CloseClicked(object sender, RoutedEventArgs e)
{
ImagePreviewBox.Source = null;
}
But i kept getting the same exception.
Where that file is being used in my program when i click the Submit button?