如何在windows应用程序中使用wpf和c上传文件
本文关键字:wpf 文件 windows 应用程序 | 更新日期: 2023-09-27 18:06:37
我有一个表单,上面有浏览按钮,当我点击它时,对话框打开,我现在选择了一个文件,该文件的路径或文件名将显示在文本框中,我想把它上传到特定的文件夹中,然后在我的系统上下载,请告诉我这个
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.IO;
//using System.Drawing;
using System.ComponentModel;
namespace RIS_2
{
/// <summary>
/// Interaction logic for crud.xaml
/// </summary>
public partial class crud : Window
{
public crud()
{
this.InitializeComponent();
// Insert code required on object creation below this point.
}
private void browse_btn_Click(object sender, RoutedEventArgs e)
{
Stream checkStream = null;
// OpenFileDialog op1 = new OpenFileDialog();
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Multiselect = false;
dlg.Filter = "All Image Files | *.*";
//dlg.Filter = "(*.pfw)|*.pfw|All files (*.*)|*.*";
Nullable<bool> result = dlg.ShowDialog();
// if ((bool)dlg.ShowDialog())
if(result==true)
{
try
{
if ((checkStream = dlg.OpenFile()) != null)
{
// MyImage.Source = new BitmapImage(new Uri(dlg.FileName, UriKind.Absolute));
//listBox1.Items.Add(openFileDialog.FileName);
string filename = dlg.FileName;
tb_file.Text = filename;
// tb_file.AppendText(dlg.FileName.ToString());
MessageBox.Show("Successfully done", filename);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
else
{
MessageBox.Show("Problem occured, try again later");
}
}
}
}
坦率地说,对我来说,代码看起来还可以,所以奇怪的是它不起作用。话虽如此,我建议你采取不同的方法。您使用的是WPF,它非常擅长数据绑定。如果您在代码后面定义属性
private string _fileName;
public string FileName
{
get{return _fileName;}
set{
_fileName = value;
OnPropertyChanged("FileName");
}
OnPropertyChanged的实现和INotifyPropertyChanged简单解释可以在http://www.java2s.com/Tutorial/CSharp/0470__Windows-Presentation-Foundation/RaisethePropertyChangedevent.htm
在XAML中,您已经有一个TextBlock,应该使用绑定进行扩展
TextBlock x:Name="tb_file" Text="{Binding Path=Filename}"
为了确保绑定到代码隐藏中的属性,请参阅代码隐藏中定义的绑定对象
希望这能有所帮助(至少是你问题的第一部分(