更换头像

问题描述 投票:0回答:1

Visual Studio 2022。C#。 WPF。 NET8.0 在设置过程中,我的应用程序要求提供特定尺寸的个人资料图片。如果用户添加它,它会保存在某个文件夹中作为“ProfilePic”。如果用户不添加,则继续使用临时配置文件。设置完成后,图像将出现在登录页面和设置页面中。现在,如果用户想要更改个人资料图片,他/她可以转到“设置”,单击图像进行更改。该代码不起作用。如果在设置过程中未添加个人资料图片,则代码可以正常工作。但是,如果添加了它并且用户希望替换它,我希望应用程序删除现有的“个人资料图片”并使用相同的名称保存新图像。但我收到错误“该进程无法访问该文件,因为它正在被另一个进程使用。”

private void Image1_Click(object sender, MouseButtonEventArgs e)

if (!isImageClickHandled)
{
    OpenFileDialog openFileDialog = new OpenFileDialog
    {
        Filter = "Image files (*.png;*.jpeg;*.jpg;*.gif)|*.png;*.jpeg;*.jpg;*.gif|All files (*.*)|*.*",
        Title = "Select an Image"
    };

    if (openFileDialog.ShowDialog() == true)
    {
        isImageClickHandled = true;

        string selectedImagePath = openFileDialog.FileName;

        // Save in "Media" folder that is in the project resources directory
        string mediaFolder = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Media");

        if (!Directory.Exists(mediaFolder))
            Directory.CreateDirectory(mediaFolder);

        // Check if profile pic already exists and delete it
        string profilePicPath = System.IO.Path.Combine(mediaFolder, "ProfilePic" + System.IO.Path.GetExtension(selectedImagePath));
        if (File.Exists(profilePicPath))
            File.Delete(profilePicPath);

        string destinationPath = System.IO.Path.Combine(mediaFolder, "ProfilePic" + System.IO.Path.GetExtension(selectedImagePath));
        File.Copy(selectedImagePath, destinationPath, true);

        BitmapImage bitmapImage = new BitmapImage(new Uri(destinationPath));
        Image1.Source = bitmapImage;

        isImageClickHandled = false;
    }
}

}

c# wpf visual-studio-2022 .net-8.0
1个回答
0
投票

当您向

BitmapImage
提供一个简单的 URI 时,它将在图像的生命周期内保持文件位置打开(如果在磁盘上)。相反,在构建图像时,您可以自己将磁盘上的数据读取到
MemoryStream
中,并使用它来构建
BitmapImage
:

        using (var str = System.IO.File.OpenRead(destinationPath))
        {
            var ms = new MemoryStream();
            str.CopyTo(ms);
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = ms;
            bitmapImage.EndInit();
            Image1.Source = bitmapImage;
        }
© www.soinside.com 2019 - 2024. All rights reserved.