繁体   English   中英

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

[英]Save Files In WPF Application. C#

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

例如文本文件

那是因为您不保存图像。 我对您上传的意思有点困惑。 但我尝试解释一下我认为对您有帮助的事情。

您应该在“ Save the image ”附近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 imageop.FileName的位置并存储其URL,在Save the image部分中,您将存储op.FileName并在下次加载时尝试从该地址加载图像。 您应该处理不可用的文件。

2-当用户删除原始文件时,请保存图像副本以安全使用。 如果是这种情况,则应将整个图像存储在“ Save the image部分”中,并下次从用户文件系统内的安全位置加载它。

希望我能解决您的问题,对您有所帮助:)

-编辑-

在注释中澄清之后,我可以详细说明:

您需要使用图像创建Base64的函数:

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

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

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中存储的图像。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM