簡體   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