在WPF应用程序中保存文件。 C#

时间:2017-01-14 23:36:00

标签: c# wpf

我想知道如何将页面上传的文件存储到设置中?

例如文本文件

1 个答案:

答案 0 :(得分:0)

那是因为你没有保存图像。 虽然上传你的意思,但我有点困惑。但我试着解释一下我认为会对你有所帮助。

你应该做你的"上传"约Save the image附近:

if (op.ShowDialog() == true)
{
    //Save the image
    image1.Source = new BitmapImage(new Uri(op.FileName));
    MessageBox.Show("File uploaded sucessfully");
}

上传最让您想到的是您希望将图像上传到服务器。为此,您将不得不使用接收图像数据的Web服务。在下一页刷新中,您需要其他服务才能接收以前上传的图像并将其显示给用户。

如果您希望应用程序将用户图像存储在其文件系统中(例如专辑应用程序),则有两种模式。

1-将文件保存在他们的位置,并在Save the image部分中存储他们的URL,然后存储op.FileName,并在下次加载时尝试从该地址加载图像。您当然应该处理文件不可用。

2-存储图像副本​​,以便在用户删除原始文件时安全使用。如果是这种情况,您应该将整个图像存储在Save the image部分,然后从用户文件系统内的安全位置加载它。

希望我得到你的问题,这有助于你:)

- 编辑 -

在评论澄清之后我可以详细说明:

您需要使用图像创建Base64的功能:

public string FileToBase64(string Path)
{
    byte[] imageArray = System.IO.File.ReadAllBytes(Path);
    return Convert.ToBase64String(imageArray);
}

另一个用于在DB中存储字符串。这部分取决于您的数据库结构和技术,但我相信您可以弄清楚:

public void SaveTheImageToDb(string Data) { }

用于将字符串分配给WPF图像的转换器:

public class Base64ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string s = value as string;

        if (s == null)
            return null;

        BitmapImage bi = new BitmapImage();

        bi.BeginInit();
        bi.StreamSource = new MemoryStream(System.Convert.FromBase64String(s));
        bi.EndInit();

        return bi;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后在你的代码中:

if (op.ShowDialog() == true)
{
    var imageData = FileToBase64(op.FileName);
    SaveTheImageToDb(imageData);
    image1.Source = new BitmapImage(new Uri(op.FileName));
    MessageBox.Show("File uploaded sucessfully");
}

在下次加载视图时,您可以使用绑定和转换器显示来自Db的存储图像。